Reputation: 3243
I have a list of dictionaries in Python and I want to check if an dictionary entry exists for a specific term. It works using the syntax
if any(d['acronym'] == 'lol' for d in loaded_data):
print "found"
but I also want to get the value stored at this key, I mean d['acronym']['meaning']. My problem is that when I try to print it out Python does not know about d. Any suggestions, maybe how can I get the index of the occurence without looping again through all the list? Thanks!
Upvotes: 0
Views: 193
Reputation: 91099
firstone = next((d for d in loaded_data if d['acronym'] == 'lol'), None)
gives you the first dict where the condition applies, or None
if there is no such dict.
Upvotes: 0
Reputation: 353339
If you know there's at most one match (or, alternatively, that you only care about the first) you can use next
:
>>> loaded_data = [{"acronym": "AUP", "meaning": "Always Use Python"}, {"acronym": "GNDN", "meaning": "Goes Nowhere, Does Nothing"}]
>>> next(d for d in loaded_data if d['acronym'] == 'AUP')
{'acronym': 'AUP', 'meaning': 'Always Use Python'}
And then depending on whether you want an exception or None
as the not-found value:
>>> next(d for d in loaded_data if d['acronym'] == 'AZZ')
Traceback (most recent call last):
File "<ipython-input-18-27ec09ac3228>", line 1, in <module>
next(d for d in loaded_data if d['acronym'] == 'AZZ')
StopIteration
>>> next((d for d in loaded_data if d['acronym'] == 'AZZ'), None)
>>>
You could even get the value and not the dict directly, if you wanted:
>>> next((d['meaning'] for d in loaded_data if d['acronym'] == 'GNDN'), None)
'Goes Nowhere, Does Nothing'
Upvotes: 3
Reputation: 29804
You can just use filter
function:
filter(lambda d: d['acronym'] == 'lol', loaded_data)
That will return a list of dictionaries containing acronym == lol
:
l = filter(lambda d: d['acronym'] == 'lol', loaded_data)
if l:
print "found"
print l[0]
Don't even need to use any
function at all.
Upvotes: 2
Reputation: 31270
any()
only gives you back a boolean, so you can't use that. So just write a loop:
for d in loaded_data:
if d['acronym'] == 'lol':
print "found"
meaning = d['meaning']
break
else:
# The else: of a for runs only if the loop finished without break
print "not found"
meaning = None
Edit: or change it into a slightly more generic function:
def first(iterable, condition):
# Return first element of iterable for which condition is True
for element in iterable:
if condition(element):
return element
return None
found_d = first(loaded_data, lambda d: d['acronym'] == 'lol')
if found_d:
print "found"
# Use found_d
Upvotes: 0
Reputation: 122090
If you want to use the item, rather than just check that it's there:
for d in loaded_data:
if d['acronym'] == 'lol':
print("found")
# use d
break # skip the rest of loaded_data
Upvotes: 0