Justas Justas - 5 months ago 6x
Python Question

List of dictionary to an expresion

Python v3.4.3

Given list of dictionaries:

dlist = [{'Bilbo':'Ian','Frodo':'Elijah'},{'Bilbo':'Martin','Thorin':'Richard'}]

and a variable k

k = 'Frodo'

Task is to write an expresion to asign list from dictionary, where key doesn't exist must be shown 'not present', all problem must be solved in 1 line.

I have written line that gives desirable output :

for kk in dlist : kk[k] if k in kk else 'NOT PRESENT'

the output:


but the problem is that I can't assign this output to variable

res = list(for kk in dlist : kk[k] if k in kk else 'NOT PRESENT')


res = [for kk in dlist : kk[k] if k in kk else 'NOT PRESENT']

In addition this gives correct assignment if all dictionaries have desired key

res = [x[k] for x in dlist]

but I cant combine
dictionary[key] if 'key' in dictionary

with for kk in dictionarylist

After abhinsit answered this question and gave me some insights: I've solved it without .get

output = [item[k] if k in item else 'NOT PRESENT' for item in dlist]

The main problem for me was the correct position of else statement.

>>> dlist = [{'Bilbo':'Ian','Frodo':'Elijah'},{'Bilbo':'Martin','Thorin':'Richard'}]
>>> required_key = 'Frodo'
>>> output = [item.get(required_key,'NOT PRESENT')for item in dlist]
>>> output
['Elijah', 'NOT PRESENT']