【问题标题】:Python creating two dictionaries, matching keys and print valuePython创建两个字典,匹配键和打印值
【发布时间】:2017-02-03 01:14:59
【问题描述】:

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

【问题讨论】:

    标签: python dictionary compare key


    【解决方案1】:

    检查字典 (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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多