Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a list of values with the same key from a dictionary

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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'}.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading