This is my example:
dictlist = [{\'first\': \'James\', \'last\': \'Joule\'},
{\'first\': \'James\',\'last\': \'Watt\'},
{\'first\':
This is very simple solution with list comprehension:
>>> dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
>>> [x['last'] for x in dictlist if x['first'] == 'Christian']
['Doppler']
for comp in dictlist:
if comp["first"] == 'Christian':
return comp["last"]
I sometimes like to use next:
next((d['last'] for d in dictlist if d['first'] == 'Christian'), None)
# 'Doppler'
The first argument is an iterator and the second (optional) argument is the default value returned if no matching entry is found.
Note: this will only return the first matching result. So it wouldn't be good if you expect to have multiple records matching your "query".
dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
the_jameses = [d for d in dictlist if d['first'] == 'James']
Where the resulting list
contains only:
[{'first': 'James', 'last': 'Joule'}, {'first': 'James', 'last': 'Watt'}]
Something like this should work
last_name = ''
for d in dictList:
if d['first'] == 'Christian':
last_name = d['last']
break