[英]Merge two list of dictionaries based on specific key
Ok, so I have this code. 好的,所以我有这个代码。
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
The problem is that this will merge every value(that's not 'id') in data2 into data1. 问题是,这会将data2中的每个值(不是'id')合并到data1中。 I only want it to merge the key 'score', but I'm really not sure how to specify that key only.
我只希望它合并键'得分',但我真的不知道如何仅指定该键。 I've tried multiple other conditional statements in order to specify the 'score' key.
我已经尝试了多个其他条件语句来指定'score'键。 But I can't seem to get anything working.
但我似乎无法得到任何工作。
Thanks for any help 谢谢你的帮助
You could factory function like this 你可以像这样工厂
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}]
Here's code that will merge the way you want. 这里的代码将以您想要的方式合并。 Note that if there are multiple lists in
data2
with the correct matching key only the first one will be found. 请注意,如果
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
output 产量
[{'score': 100, 'Id': 1}, {'score': 200, 'Id': 2}]
If we change data1
to 如果我们将
data1
更改为
data1 = [
{'Id': 1},
{'Id': 5},
{'Id': 2},
]
Then we get this output: 然后我们得到这个输出:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.