Teofrostus
Teofrostus

Reputation: 1596

Construct two lists from a list of dictionaries in python

I have a list of dictionaries with 2 or more keys, and I want to construct 2 or more lists based on those keys. For example:

dict_list = [{'key1':1, 'key2':2}, {'key1': 3, 'key2':4}, ... ]

should become

list1 = [1, 3, ...]
list2 = [2, 4, ...]

To construct a single list, there's the elegant solution:

list1 = [item['key1'] for item in dict_list]

However, doing this twice would be inefficient. Is there an efficient and elegant or Pythonic way of doing this? The other solution I have is something like:

list1 = []
list2 = []
for item in dict_list:
    list1.append(item['key1'])
    list2.append(item['key2'])

but, of course, this feels less elegant than some sort of list comprehension technique.

Upvotes: 2

Views: 88

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49318

I recommend making a single dictionary with keys like the original dictionaries and values of lists containing each of the original dictionaries' appropriate values:

>>> dict_list = [{'key1':1, 'key2':2}, {'key1': 3, 'key2':4}]
>>> dct = {}
>>> for d in dict_list:
...     for k in d:
...         dct.setdefault(k, []).append(d[k])
...
>>> dct
{'key1': [1, 3], 'key2': [2, 4]}

Upvotes: 1

Related Questions