Continued from this stackoverflow question.
I have the following data structure:
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
I want to search all ‘site’ keys for a specific value, and return that dictionary’s ‘id’ value. For example, searching ‘Superuser’ should return 2:
>>> print find_id('Superuser')
2
When I tried using the referenced question’s solution, I received an error:
>>> if any(d['site'] == 'Superuser' for d in data): print d['Superuser']
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
>>> if any(d['site'] == 'Superuser' for d in data): print data['Superuser']
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
What’s the most pythonic way of doing this?
No tricks here. Just do: