Python创建两个词典,匹配键和打印值

时间:2017-02-03 01:15:00

标签: python dictionary compare key

如何从一个字典中获取信息以在另一个字典中查找关联的名称?例如,我创建的一个字典包含系统中所有用户的名称,电子邮件地址和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'])

1 个答案:

答案 0 :(得分:0)

检查dict中的存在(if key in user)只能看到dict的键,而不是你想要的。您想要比较值,特别是'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)