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.
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)]]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With