3

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:

'Elijah'
'NOT PRESENT'

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')

or

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

EDIT: 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.

Cœur
  • 32,421
  • 21
  • 173
  • 232
lescijus
  • 76
  • 6

1 Answers1

2
>>> 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']
>>> 
abhinsit
  • 2,962
  • 4
  • 16
  • 24
  • Ty for your answer it gives desirable result, but the same task is doable without using item.get. – lescijus Apr 26 '16 at 06:07
  • yes there are different ways to get / check value in a dictionary, it all depends how you want to implement it. You may have written a if instead of get – abhinsit Apr 26 '16 at 06:13
  • Yes the problem for me was that else is mandatory, and else position must be not at the very end, with your advise I get desirable output with if [item[k] if k in item else 'NOT PRESENT' for item in dlist] – lescijus Apr 26 '16 at 06:17