当2在字典中时,如何查找与某个人的“姓名”相关联的“id”?
user = 'PersonA'
id = ? #How do I retrieve the 'id' from the user_stream json variable?
[
{
'name': 'PersonA',
'id': '135963'
},
{
'name': 'PersonB',
'id': '152265'
},
]
答案 0 :(得分: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')
如果您需要进行多次查找,您可能希望将此结构转换为dict
以简化查找:
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
这一直是一种权衡,你为了速度而交换记忆。
答案 1 :(得分: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]
答案 2 :(得分:0)
persons = json.loads(...)
results = filter(lambda p:p['name'] == 'avi',persons)
if results:
id = results[0]["id"]
results
当然可以超过1个。