我有2个带有数组的字典。我只想在主要列表中使用字典,只要“桶”出现在字典“桶”的辅助列表中,而“标签”是匹配的。
primary = [{'buckets': [165, 27],
'label': 'Andrew'}, {'buckets': [1364],
'label': 'Matt'},{'buckets':[500, 60, 888], 'label':'John'}]
secondary = [{'buckets': [165, 1447],
'label': 'Andrew'}, {'buckets': [1365, 15, 16],
'label': 'Matt'}, {'buckets':[12,10,15], 'label':'Max'}]
data = {}
for x in primary:
found = False
for i in secondary:
for num in x['buckets']:
if x['label'] == i['label']:
if num in i['buckets']:
found =True
break
if found:
data[x['label']] = x['buckets']
else:
data[i['label']] = i['buckets']
pprint.pprint(data)
如果我更改数组中的匹配/数字,我得不到正确的结果。任何帮助将不胜感激。
Desired output:
{'Andrew': [165, 27], 'Matt': [1365, 15, 16]}
这有时会发生,但如果我改变次要的安德鲁斯数字它可能最终只是这个。
{'Matt': [1365, 15, 16]}
这是一个解决方案。我在这里使用的主要观点是intersection
来检查两个列表之间是否存在共同值。如果有,那么我从primary
获取列表。如果没有,那么你从secondary
获取列表,正如你在下面的评论中解释的那样。你现在不需要found
标签
data = {}
for x in primary:
for i in secondary:
if x['label'] == i['label']:
if list(set(x['buckets']).intersection(i['buckets'])):
data[x['label']] = x['buckets']
break
else:
data[x['label']] = i['buckets']
print(data)
# {'Andrew': [165, 27], 'Matt': [1365, 15, 16]}