I have a list of dictionaries similar to the following. The actual data contains arbitrarily many keys, this is just a sample of the data:
l = [{'name': 'jamie', 'age': 26},
{'name': 'tara', 'age': 43},
{'name': 'matt', 'age': 34}
]
What I need to do is to access the values of the name and age keys and have them as a list like the following:
[['jamie', 'tara', 'matt'], [26, 43, 34]]
I know that if I need to create a list of a single key, I can print their values using the following code:
[d["name"] for d in l]
However, that code only returns the following output:
['jamie', 'tara', 'matt']
Could anyone help me how to return all values as list of lists? Also, considering that there are going to be many keys in my real list, it is possible to write the code in a way that I don’t need to specify the key names?
>Solution :
You can use zip:
l = [{'name': 'jamie', 'age': 26, 'hobby': 'fishing'},
{'name': 'tara', 'age': 43, 'hobby': 'soccer'},
{'name': 'matt', 'age': 34, 'hobby': 'knitting'}]
output = list(zip(*(dct.values() for dct in l))) # first method
print(output)
# [('jamie', 'tara', 'matt'), (26, 43, 34), ('fishing', 'soccer', 'knitting')]
keys = l[0].keys() # second method
output = list(zip(*([dct[k] for k in keys] for dct in l)))
print(output)
Here, the first method works if the keys are ordered the same (so works on python 3.7+). The second one works even if, say, the second dict is {'age': 43, 'name': 'tara', 'hobby': 'soccer'}.