如何从一个字典中获取信息以在另一个字典中查找关联的名称? 例如,我创建的一个词典包含系统中所有用户的名称、电子邮件地址和 ID。 另一个字典只包含一个 id。
我想从成绩单中获取 id,并查看是哪个用户编写了成绩单。 id 是一个数字字符串
这是我所拥有的,但无论我输入transcript_id号码如何,它都返回相同的用户名。
transcript = transcript.find(id=transcript_id)
for admin in category.all():
user = {'name': admin.name, 'id': admin.id, 'email': admin.email }
for part in transcript.transcript_parts:
transcript_author = { 'id': part.author.id }
for key in transcript_author:
if key in user:
print(user['name'])
检查字典中的存在 ( if key in user
) 只在字典的键中查找,这不是您想要的。您希望比较值,特别是'id'
键的值。
考虑一下:
>>> user = {'name': 'chrism1148', 'id': '12345', 'email': None}
>>> '12345' in user
False # fails as '12345' is not one of the keys
>>> 'id' in user
True # succeeds as 'id' is a key
>>> '12345' == user['id']
True # this works, but will throw an exception if 'id' is not in the dict for some reason
>>> '12345' == user.get('id', None)
True # it's a good idea to use this instead (None is used as a default value for when 'id' is not present in the dict)