Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将两个列表(一个包含重复元素,一个包含整数)合并到dict中_Python_List_Dictionary_Merge_Add - Fatal编程技术网

Python 将两个列表(一个包含重复元素,一个包含整数)合并到dict中

Python 将两个列表(一个包含重复元素,一个包含整数)合并到dict中,python,list,dictionary,merge,add,Python,List,Dictionary,Merge,Add,因此,我有两个列表,它们是通过基于几个参数获取JSON数据创建的,例如: list_1 = ['red', 'green', 'blue', 'yellow', 'red', 'blue', 'pink') list_2 = [0.1, 0.1, 0.7, 0.4, 0.5, 0.6, 1.5] 在JSON数据中,键'red'在一个嵌套数组中的值为0.1,在另一个嵌套数组中的值为0.5。列表按顺序排列,因此list\u 1[0]对应于list\u 2[0]和list\u 1[1]对应于list

因此,我有两个列表,它们是通过基于几个参数获取JSON数据创建的,例如:

list_1 = ['red', 'green', 'blue', 'yellow', 'red', 'blue', 'pink')
list_2 = [0.1, 0.1, 0.7, 0.4, 0.5, 0.6, 1.5]
在JSON数据中,键
'red'
在一个嵌套数组中的值为
0.1
,在另一个嵌套数组中的值为
0.5
。列表按顺序排列,因此
list\u 1[0]
对应于
list\u 2[0]
list\u 1[1]
对应于
list\u 2[1]

我的目标是最终得到一个字典,其中有来自
list_1
的唯一元素和来自
list_2
的组合值。例如:

list_1 = ['red', 'green', 'blue', 'yellow', 'red', 'blue', 'pink')
list_2 = [0.1, 0.1, 0.7, 0.4, 0.5, 0.6, 1.5]
dict_1={'red':0.6,'green':0.1,'blue':1.3,'yellow':0.4,'pink':1.5}

我一直在玩弄
zip
zip\u longest
map
,但我发现这些都不管用。关于如何获取JSON数据,我已经回到了绘图板上,但是如果有人有一段整洁的代码,那就太棒了。

您可以使用生成对并对其进行迭代:

list_1 = ['red', 'green', 'blue', 'yellow', 'red', 'blue', 'pink']
list_2 = [0.1, 0.1, 0.7, 0.4, 0.5, 0.6, 1.5]

res = {}
for key, value in zip(list_1, list_2):
    if key in res:
        res[key] += value
    else:
        res[key] = value

您可以为此使用
defaultdict

list_1 = ['red', 'green', 'blue', 'yellow', 'red', 'blue', 'pink']
list_2 = [0.1, 0.1, 0.7, 0.4, 0.5, 0.6, 1.5]

from collections import defaultdict

res = defaultdict(float)

for k, v in zip(list_1, list_2):
    res[k] += v

这不起作用,因为红色的值将是0.5,而不是0.6,因为字典不允许多个键。@t.BJ,检查post editsEven,如果它起作用,将
float
作为默认类型传递是正确的。@OlvinRoght忽略了这一点,谢谢。基本上与dupe中的想法相同,只是压缩了对。