jpaulc
jpaulc

Reputation: 33

PYTHON: getting all values in a dict inside a list

I have a list of dictionaries and i want to get the values by using the keys.

I have this list as a headers:

headers = ['color','age','name']

And this list of dictionaries as contents:

contents =[{'name':'bryan','age':'4','color':'white'},{'age':'3','name':'gordon'},{'name':'jordan','color':'black','age':'2'}]

and i have this code to get all the values in it using the headers

res = [list(itemgetter(*headers)(i)) for i in contents]

But I am getting an

ErrorKey: 'color'

because there's no key ("color" - based from the headers) in the dictionary.

Now i am confused, Can someone help me figure out on how to "not to get an error" when running my code.

Upvotes: 1

Views: 686

Answers (3)

Red
Red

Reputation: 27577

Here is how you can do that with a nested list comprehension:

headers = ['color','age','name']

contents =[{'name':'bryan','age':'4','color':'white'},{'age':'3','name':'gordon'},{'name':'jordan','color':'black','age':'2'}]

res = [list(i.get(d) for d in headers) for i in contents]

print(res)

Output:

[['white', '4', 'bryan'], [None, '3', 'gordon'], ['black', '2', 'jordan']]

If you want to omit the Nones:

res = [list(i.get(d) for d in headers if i.get(d) != None) for i in contents]

Output:

[['white', '4', 'bryan'], ['3', 'gordon'], ['black', '2', 'jordan']]

Upvotes: 1

kederrac
kederrac

Reputation: 17322

you can use your headers as a set and then unpack for itemgetter parameters the intersection between your heders and the keys from your actual dictionary:

headers = {'color','age','name'}
contents =[{'name':'bryan','age':'4','color':'white'},{'age':'3','name':'gordon'},{'name':'jordan','color':'black','age':'2'}]

res = [list(itemgetter(*headers.intersection(i))(i)) for i in contents]
# [['bryan', '4', 'white'], ['gordon', '3'], ['jordan', '2', 'black']]

or you can use a list comprehension:

res = [[d[h] for h in headers if h in d] for d in contents]
# [['bryan', '4', 'white'], ['gordon', '3'], ['jordan', '2', 'black']]

Upvotes: 2

Jay
Jay

Reputation: 2888

Try:

[dic.get(key) for key in headers for dic in contents]

Result:

['white', None, 'black', '4', '3', '2', 'bryan', 'gordon', 'jordan']

If you don't want the Nones, a slight modification on your version using set intersection:

[list(itemgetter(*set(headers) & dic.keys())(dic)) for dic in contents]

Result:

 [['white', 'bryan', '4'], ['gordon', '3'], ['2', 'jordan', 'black']]

If you use the second variation, you probably want the headers as a set in advance to avoid reapplying:

headers = set(headers)

Upvotes: 2

Related Questions