python字典-合并两个字典,并在匹配时附加键值

时间:2019-11-04 19:10:18

标签: python-3.x dictionary-comprehension

我有两个字典清单。一种是嵌套的层次结构格式,另一种是简单的字典列表。我正在尝试像我们在熊猫或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匹配,我将尝试匹配,然后填充辅导员,“将”评分为字典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'],
           }}
]

1 个答案:

答案 0 :(得分:1)

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

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}
相关问题