简体   繁体   中英

List of dictionaries with comprehension in python

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.

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)]

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)]]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM