0

当 2 在字典中时,如何查找与一个人的“姓名”相关的“id”?

user = 'PersonA'
id = ? #How do I retrieve the 'id' from the user_stream json variable?

json,存储在名为“user_stream”的变量中

[
  {
    'name': 'PersonA',
    'id': '135963'
  },
  {
    'name': 'PersonB',
    'id': '152265'
  },
]
4

3 回答 3

2

您必须解码 JSON 结构并遍历所有字典,直到找到匹配项:

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')

如果您需要进行多次查找,您可能希望将此结构转换为 adict以简化查找:

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

然后直接查找id

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

上面的示例假定名称是唯一的,如果不是,请使用:

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

这始终是一种权衡,您以内存换取速度。

于 2012-11-28T15:22:58.623 回答
1

Martijn Pieters 的解决方案是正确的,但如果您打算进行许多此类查找,最好加载 json 并仅对其进行一次迭代,而不是每次查找。

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]
于 2012-11-28T15:28:35.823 回答
0
persons = json.loads(...)
results = filter(lambda p:p['name'] == 'avi',persons)
if results:
    id = results[0]["id"]

results当然可以超过1..

于 2012-11-28T15:29:25.550 回答