【问题标题】:python dictionary - merge two dictionary and append key values if they matchpython字典 - 合并两个字典并在它们匹配时附加键值
【发布时间】:2019-11-04 19:10:18
【问题描述】:

我有两个字典列表。一种是嵌套的分层格式,另一种是简单的字典列表。我正在尝试像我们在 pandas 或 sql 中那样做的“外部连接”,比如“加入”。基本上,我试图从字典中捕获键/值,而另一个键/值不存在。这是我尝试过的。

字典 1: 大型嵌套字典:

data = [
    {'file_name': 'abc.pdf',
     'year':'2016',
      'overview': {
          'student_id': '123abc',
           'name': 'Adam Smith',
           'courses': ['Math', 'Physics'],
           }},

    {'file_name': 'def.pdf',
     'year':'2017',
      'overview': {
          'student_id': '123abc',
           'name': 'Adam Smith',
           'courses': ['Arts'],
           }}
]

字典 2:

mapper =[{
    'year':'2016',
    'student_id': '123abc',
    'counselor':'Matthews',
    'grades':'85'
}]

尝试/合并

pairs = zip(mapper,data)

试试 1

[(x,y) for x, y in pairs if x['student_id'] == y['overview']['student_id']]

>> gives result:
[({'year': '2016',
   'student_id': '123abc',
   'counselor': 'Matthews',
   'grades': '85'},
  {'file_name': 'abc.pdf',
   'year': '2016',
   'overview': {'student_id': '123abc',
    'name': 'Adam Smith',
    'courses': ['Math', 'Physics']}})]

尝试 2:

[(x,y) for x, y in pairs if x['student_id'] == y['overview']['student_id'] & x['year'] == y['year']]
# gives errors: `TypeError: unsupported operand type(s) for &: 'str' and 'str'`

试图得到这个结果:如果两个字典中的 year 和 student_id 匹配,那么给出这个结果。从字典 2:如果 year 和 student_id 匹配,我试图匹配然后填充辅导员,'grades' 到字典 1。如果不匹配,则给定字典元素。

new_data = [
    {'file_name': 'abc.pdf',
     'year':'2016',
      'overview': {
          'student_id': '123abc',
           'name': 'Adam Smith',
           'courses': ['Math', 'Physics'],
            'counselor':'Matthews',
            'grades':'85'
           }},

    {'file_name': 'def.pdf',
     'year':'2017',
      'overview': {
          'student_id': '123abc',
           'name': 'Adam Smith',
           'courses': ['Arts'],
           }}
]

【问题讨论】:

    标签: python-3.x dictionary-comprehension


    【解决方案1】:

    我认为zip 在这种情况下不是一个好的选择。我会将数据的 ['overview'] 字典与映射器字典合并:

    for idx, i in enumerate(data):
        for j in mapper:
            if i['overview']['student_id'] in j['student_id'] and i['year'] == j['year']:
                data[idx]['overview'] = {**i['overview'], **j}
    

    【讨论】:

    • @StaticX 感谢您提供上述解决方案。我能够执行它。但是,它仍然是我在我的问题上面的输出中寻找的东西。当 student_id 和 year 都从字典 2 匹配到字典 1 时,我试图获取键/值。在你的情况下,它只匹配 'student_id' 而不是 'year'。我试过这个i['overview']['student_id'] in j['student_id'] and i['year'] in j['year'] 但没用
    • 好的@sharp 我已经更新它以匹配年份。在这种情况下,您只需要 ==,因为它是单个值,而不是字典。
    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    相关资源
    最近更新 更多