Skip to content

Instantly share code, notes, and snippets.

@szeitlin
Created February 18, 2015 17:35
Show Gist options
  • Select an option

  • Save szeitlin/d7d8758669d2b5ab06cb to your computer and use it in GitHub Desktop.

Select an option

Save szeitlin/d7d8758669d2b5ab06cb to your computer and use it in GitHub Desktop.
iterate dict list comprehension
dlist = [{'Bilbo':'Ian','Frodo':'Elijah'},
{'Bilbo':'Martin','Thorin':'Richard'}]
k = 'Bilbo'
#this works as expected
for i in dlist:
... if k in i:
... i[k]
... else:
... 'NOT PRESENT'
#it also works with this
k= 'Frodo'
#iteration goes at the end in this case!!
[i[k] if k in i else 'NOT PRESENT' for i in dlist]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment