【发布时间】:2020-10-20 08:21:00
【问题描述】:
我有一个结构数据:
matches = [
{
"15477084": [1]
},
{
"360418": [2]
},
{
"15477084": [1]
},
{
"15477084": [3,4]
}
]
我想检查键中的键和值是否重复,我将其删除。如果 key 和 value 有很多不同的值,我会把它结合起来。
我希望我的结果像:
matches = [
{
"15477084": [1,3,4]
},
{
"360418": [2]
}
]
这是我的代码:
new_matches = []
for j in matches:
newdict = dict()
for key,value in j.items():
if key in newdict.keys():
if value not in newdict[key]:
newdict[key].append(value)
new_matches.append(newdict)
else:
newdict[key] = value
new_matches.append(newdict)
但我的结果是错误的(我的结果与数据匹配开始相同)。我不知道为什么我的结果是错误的。
【问题讨论】:
-
为什么
15477084有[1,2,3]而不是[1,1,3,4]?对于您的代码,您在每次迭代中都创建了空字典newdict,因此if key in newdict.keys()将始终为False,因此与原始输入没有区别。 -
@Chris 我已尝试将
newdict定位在循环之外for j in matches,但它不起作用。我想根据键删除重复值,所以15477084需要有[1,3,4]
标签: python python-3.x list dictionary duplicates