【问题标题】:Query cross referencing dictionaries查询交叉引用字典
【发布时间】:2018-05-02 02:47:18
【问题描述】:

我被一些列表/字典工作困住了。这是我拥有的第一个字典列表的一部分

{'createdTime': '2017-11-18T11:11:42.223Z',
 'fields': {'Pair ID': 307,
            'Source': ['recmSPeRUDk7JxTEs'],
            'Target': ['recEijqlS0kjmIjpL']},
 'id': 'rec02AuJ8QzEZR56b'}

SourceTarget 中,它引用了另一个字典中的条目,看起来像这样(被此处不相关的所有内容剥离)

{'createdTime': '2017-11-05T17:14:59.000Z',
 'fields': {'Name': 'John',
            'E-Mail': 'john@example.com ',
 'id': 'rec0KMaG8L7qldPuI'}

链接是通过 id 字段。因此,上述字典中的 Source 和 Target 在第二个中引用了一个条目。我知道在遍历列表时需要向上述字典中的每个 Source 发送电子邮件。

两者都是字典列表。我的问题是我是否也需要遍历第二个列表,或者有没有办法以更智能的方式引用与上面的 Source 匹配的记录?

【问题讨论】:

    标签: python python-3.x list dictionary iteration


    【解决方案1】:

    由于数据的格式化方式,答案是肯定的,您必须进行迭代,因为当您知道键并且想要获得相应的值时,就可以使用字典。在这里,您要检索知道值的键,这是相反的情况。

    现在,如果这是您想要的,我建议您修改数据的结构,使 id 不是字段,而是直接作为字典的键。例如:

    events_recorded = {
        'rec02AuJ8QzEZR56b' :
            {'createdTime': '2017-11-18T11:11:42.223Z',
             'fields': {
                        'Pair ID': 307,
                        'Source': ['recmSPeRUDk7JxTEs'],
                        'Target': ['recEijqlS0kjmIjpL']},
            },
        'recRkckX9nfl5VhWk' :
             {'createdTime': '2017-11-18T12:05:42.223Z',
             'fields': {
                        'Pair ID': 45,
                        'Source': ['reclfUAfAmCRlmuKw'],
                        'Target': ['recMIG7mm7eNZ79IC']},
            },
        'receeyCtLXIA2r1dw' :
             {'createdTime': '2017-11-18T12:05:42.223Z',
             'fields': {
                        'Pair ID': 45,
                        'Source': ['recnQPVxk5Lvv73xz'],
                        'Target': ['recMV3zbkgevDEgr0y']},
            },
    
    }
    
    
    addressbook = {
        'rec0KMaG8L7qldPuI' :
            {'createdTime': '2017-11-05T17:14:59.000Z',
             'fields': {'Name': 'John',
                        'E-Mail': 'john@example.com '}
             },
        'reclfUAfAmCRlmuKw' :
             {'createdTime': '2017-10-05T03:43:02.000Z',
             'fields': {'Name': 'Ehtel',
                        'E-Mail': 'ethel@example.com '}
             },
        'recMV3zbkgevDEgr0y' :
             {'createdTime': '2017-10-05T03:43:02.000Z',
             'fields': {'Name': 'Gertrude',
                        'E-Mail': 'gertrude@example.com '}
             },
    
        }
    

    然后您可以执行以下操作:

    reference_wanted = events_recorded['rec02AuJ8QzEZR56b']['fields']['Source'][0]
    email_wanted = addressbook[reference_wanted]['fields']['E-Mail']
    

    但这取决于您的数据的结构

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      相关资源
      最近更新 更多