0

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'
  },
]

3 Answers 3

2

You'll have to decode the JSON structure and loop through all the dictionaries until you find a match:

for person in json.loads(user_stream):
    if person['name'] == user:
        id = person['id']
        break
else:
    # The else branch is only ever reached if no match was found
    raise ValueError('No such person')

If you need to make multiple lookups, you probably want to transform this structure to a dict to ease lookups:

name_to_id = {p['name']: p['id'] for p in json.loads(user_stream)}

then look up the id directly:

id = name_to_id.get(name)  # if name is not found, id will be None

The above example assumes that names are unique, if they are not, use:

from collections import defaultdict

name_to_id = defaultdict(list)
for person in json.loads(user_stream):
    name_to_id[person['name']).append(person['id'])

# lookup
ids = name_to_id.get(name, [])  # list of ids, defaults to empty

This is as always a trade-off, you trade memory for speed.

Sign up to request clarification or add additional context in comments.

7 Comments

There's no way to do it without looping? I can't "search" for PersonA?
@sharataka: Not in a manner that'll work with all JSON formatting variations, no.
Thanks, what do you mean by all JSON formatting variations though?
Shouldn't the else block be indented on the same level as the if block?
@DavidPärsson: No, it goes with the for loop. It is executed if we didn't break out of the loop.
|
1

Martijn Pieters's solution is correct, but if you intend to make many such look-ups it's better to load the json and iterate over it just once, and not for every look-up.

name_id = {}

for person in json.loads(user_stream):
    name = person['name']
    id = person['id']
    name_id[name] = id

user = 'PersonA'
print name_id[user]

1 Comment

+1. If your data doesn't come with a structure that suits your intended use, then a good practice is to restructure the data first, and then use it.
0
persons = json.loads(...)
results = filter(lambda p:p['name'] == 'avi',persons)
if results:
    id = results[0]["id"]

results can be more than 1 of course..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.