Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 932
superMind Avatar asked Mar 08 '15 08:03

superMind


2 Answers

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)]]
like image 80
Irshad Bhat Avatar answered Sep 20 '22 18:09

Irshad Bhat


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)]
like image 21
bozdoz Avatar answered Sep 18 '22 18:09

bozdoz