简体   繁体   English

将嵌套列表与字典键进行比较并创建复合键值对

[英]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.

相关问题 将嵌套列表与字典键进行比较,使用值的总和创建复合键 'a+b' - Comparing nested list with dictionary keys, create compound key 'a+b' with sum of values 如何在条件语句中使用嵌套在列表中的字典键值对的值? - How do I use the value of a key-value pair of a dictionary nested inside a list in a conditional statement? 查找字典是简单键值对还是嵌套字典 - Find whether dictionary is simple key-value pair or nested dicts 根据来自单独列表的匹配项,使用来自字典列表中的值的键值对创建一个新字典 - Create a new dictionary with the key-value pair from values in a list of dictionaries based on matches from a separate list 列表理解 - 尝试从键值对数组的数组中创建字典 - List comprehension - attempting to create dictionary from array of key-value pair arrays 如何将现有列表转换为 Python 中字典的键值对? - How to turn an existing list into a key-value pair for a dictionary in Python? 如何从列表中创建一个字典,只包含键列表和键值对(Python)? - How to create a dictionary from a list with a list of keys only and key-value pairs (Python)? 将嵌套字典展平为键:值对列表 - Flatten nested dictionary to list of key:value pair 具有不可散列键的键值对 - Key-value pair with unhashable keys 交换字典键和值仅适用于 3 个键值对字典 - Swapping dictionary keys and values works only on 3 key-value pair dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM