[英]Comparing nested list with dictionary keys and create compound key-value pair
I have a nested list and a dictionary and I want to compare list items with dictionary keys and if they match then the corresponding dictionary values should be added and appended to same dictionary new compound key-value pair as shown below:我有一个嵌套列表和一个字典,我想将列表项与字典键进行比较,如果它们匹配,则应添加相应的字典值并将其附加到相同的字典新复合键值对中,如下所示:
colours = [['red', 'yellow'], ['green', 'black'], ['white', 'blue', 'orange'], ['pink', 'purple']]
dict1 = {'red': 10, 'black': 20, 'green': 30, 'neon':5, 'yellow': 40, 'orange':50, 'white':60,
'blue':70}
It should compare complete sublist item with dictionary keys and if present then dictionary values should be summed for those keys.它应该将完整的子列表项与字典键进行比较,如果存在,则应该对这些键的字典值求和。
Expected result:预期结果:
dict1 = {'red': 10, 'black': 20, 'green': 30, 'neon':5, 'yellow': 40, 'orange':50, 'white':60,
'blue':70, 'red + yellow':50, 'green + black':50, 'white + blue +orange':180}
The list is appended by some logic and the number of elements in sublists is not fixed.列表由一些逻辑附加,子列表中的元素数量不固定。
With the help from fellow community member @tomjn I could do partially solve this problem and code is given below:在社区成员@tomjn 的帮助下,我可以部分解决这个问题,代码如下:
for i, j in itertools.combinations(itertools.chain(*colours), 2):
if i in dict1 and j in dict1:
dict1[f"{i} + {j}"] = dict1[i] + dict1[j]
Can anyone please help me complete this code?谁能帮我完成这段代码?
Thanks in advance!提前致谢!
You don't need itertools for this, just an ordinary loop over colours
.你不需要 itertools ,只是一个普通的
colours
循环。
for colorlist in colours:
if (all(c in dict1 for c in colorlist)):
dict1[" + ".join(colorlist)] = sum(dict1[c] for c in colorlist)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.