根据特定键合并两个词典列表

时间:2016-03-15 10:10:46

标签: python dictionary

好的,我有这段代码。

data1 = [
    {'Id': 1}, 
    {'Id': 2}
]
data2 = [
    {'Id': 1, 'score': 100, 'testdata': 333}, 
    {'Id': 2, 'score': 200, 'testdata': 555}, 
    {'Id': 3, 'score': 300, 'testdata': 444}
]

expectedData = [
        {'Id': 1, 'Score': 100}, 
        {'Id': 2, 'Score': 200}
    ]


def merge_lists(data1, data2, key):
    merged = {}
    for item in data1+data2:
        if item[key] in merged:
            merged[item[key]].update(item)
        else:
            merged[item[key]] = item
    return [val for (_, val) in merged.items()]

merged = merge_lists(data1, data2, 'Id')

print merged

问题是这会将data2中的每个值(不是'id')合并到data1中。我只希望它合并键'得分',但我真的不知道如何仅指定该键。我已经尝试了多个其他条件语句来指定'score'键。但我似乎无法得到任何工作。

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

你可以像这样工厂

data1 = [
    {'Id': 1},
    {'Id': 2}
]
data2 = [
    {'Id': 1, 'score': 100, 'testdata': 333},
    {'Id': 2, 'score': 200, 'testdata': 555},
    {'Id': 3, 'score': 300, 'testdata': 444}
]

def get_score(list_of_dict, id_value):

    for dict_ in list_of_dict:
        if dict_["Id"] == id_value:
            return {"score": dict_["score"]}

res = data1.copy()

for dict_ in res:
    dict_.update(get_score(data2, dict_["Id"]))

print(res)
# [{'score': 100, 'Id': 1}, {'score': 200, 'Id': 2}]

答案 1 :(得分:1)

这里的代码将以您想要的方式合并。请注意,如果data2中有多个列表使用正确的匹配键,则只会找到第一个列表。

data1 = [
    {'Id': 1}, 
    {'Id': 2},
]

data2 = [
    {'Id': 1, 'score': 100, 'testdata': 333}, 
    {'Id': 2, 'score': 200, 'testdata': 555}, 
    {'Id': 3, 'score': 300, 'testdata': 444},
]

def merge_lists(data1, data2, key):
    result = []
    for d1 in data1:
        val = d1[key]
        dnew = {key: val}
        for d2 in data2:
            if d2[key] == val:
                dnew['score'] = d2['score']
                break
        else:
            raise KeyError('No match for %r: %s' % (key, val))
        result.append(dnew)
    return result

merged = merge_lists(data1, data2, 'Id')
print merged

<强>输出

[{'score': 100, 'Id': 1}, {'score': 200, 'Id': 2}]

如果我们将data1更改为

data1 = [
    {'Id': 1}, 
    {'Id': 5},
    {'Id': 2},
]

然后我们得到这个输出:

Traceback (most recent call last):
  File "./qtest.py", line 45, in <module>
    merged = merge_lists(data1, data2, 'Id')
  File "./qtest.py", line 41, in merge_lists
    raise KeyError('No match for %r: %s' % (key, val))
KeyError: "No match for 'Id': 5"