Combining multiple lists

I have a list of dictionaries and I want to get a list of 2 keys in the list. This is how I do it now:

l_id = [d['id1'] for d in l_data]
l_id.extend([d['id2'] for d in l_data])

      

Is there a pythonic way to comprehend a list once and get the same result? (id order doesn't matter)

+3


source to share


4 answers


What about



l_id = [d[key] for key in ['id1', 'id2'] for d in l_data]

      

+4


source


You can iterate over the elements of the dictionary at each iteration and check if the key is id1

or id2

, then store the value:

[j for d in l_data for i,j in d.items() if i=='id1' or i=='id2']

      



Alternatively, you can also use operator.itemgetter

with a function map

:

>>> data = [ {'id1':1, 'col1':'va1', 'id2':1001}, {'id1':2, 'col1':'va2', 'id2':1002}]
>>> map(itemgetter('id1','id2'),data)
[(1, 1001), (2, 1002)]

      

+3


source


l_id = [d[key] for key in ('id1', 'id2') for d in l_data]

      

+1


source


If you want all the key values id1

followed by all the key values id2

, you can do it like this:

l_id = [ d[k] for k in ["id1", "id2"] for d in l_data if k in d ]

      

If you already know that every dictionary has all the required identifiers, you can skip test ( if k in d

).

+1


source







All Articles