List of dictionaries with comprehension in python

ⅰ亾dé卋堺 提交于 2021-02-18 11:22:31

问题


I have the following list of dictionaries:

    ld=[{'a':10,'b':20},{'p':10,'u':100}]

I want to write a comprehension like this:

    [ (k,v) for k,v in [ d.items() for d in ld ] ]

basically I want to iterate over dictionaries in the list and get the keys and values of each dict and do sth.

Example: One example output of this would be for example another list of dictionaries without some keys:

        ld=[{'a':10,'b':20},{'p':10,'u':100}]
        new_ld=[{'a':10},{'p':10}]

However, the above comprehension is not correct. Any help would be appreciated.


回答1:


Correct list comprehension is [[(k,v) for k,v in d.items()] for d in ld]

Demo:

>>> ld = [{'a': 10, 'b': 20}, {'p': 10, 'u': 100}]
>>> [[(k,v) for k,v in d.items()] for d in ld]
[[('a', 10), ('b', 20)], [('p', 10), ('u', 100)]]
>>> [[(k,v) for k,v in d.items() if k not in ['b','u']] for d in ld]
[[('a', 10)], [('p', 10)]]



回答2:


It looks like you want a list of tuples with the keys and values paired.

To do this you can do two for loops in a list comprehension, and use .items() to output the keys and values as tuples:

[kv for d in ld for kv in d.items()]

outputs:

[('a', 10), ('b', 20), ('p', 10), ('u', 100)]



回答3:


Use itertools.chain.from_iterable to flatten the sequence:

>>> from itertools import chain
>>> ld = [{'a':10,'b':20},{'p':10,'u':100}]
>>> list(chain.from_iterable(d.items() for d in ld))
[('a', 10), ('b', 20), ('p', 10), ('u', 100)]

The other solution is to use double-for comprehension/generator but I find them very hard to read.



来源:https://stackoverflow.com/questions/28924633/list-of-dictionaries-with-comprehension-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!