How do I look up the ‘id’ associated with the a person’s ‘name’ when the 2 are in a dictionary?
user = 'PersonA'
id = ? #How do I retrieve the 'id' from the user_stream json variable?
json, stored in a variable named “user_stream”
[
{
'name': 'PersonA',
'id': '135963'
},
{
'name': 'PersonB',
'id': '152265'
},
]
You’ll have to decode the JSON structure and loop through all the dictionaries until you find a match:
If you need to make multiple lookups, you probably want to transform this structure to a
dictto ease lookups:then look up the
iddirectly:The above example assumes that names are unique, if they are not, use:
This is as always a trade-off, you trade memory for speed.