Python 2.7:将两个具有重复值的列表放入字典

时间:2018-08-02 18:35:39

标签: python list dictionary duplicates

如果我有2个列表:

fruits = ["apple","apple","oranges","watermelon","apple"]
val = ["a","b","c","d","e"]

val的每个索引对应于水果的索引

因此,如果我要使用以下字典:

dict
{
"apple" : ["a","b","e"],
"oranges": ["c"],
"watermelon": ["d"]
}

最简单的方法是什么?

2 个答案:

答案 0 :(得分:4)

使用带有defaultdict工厂的list作为输出容器,并使用zip遍历两个列表:

In [162]: out = collections.defaultdict(list)

In [163]: for k, v in zip(fruits, val):
     ...:     out[k].append(v)
     ...:     

In [164]: out
Out[164]: 
defaultdict(list,
            {'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']})

In [165]: dict(out)
Out[165]: {'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']}

答案 1 :(得分:0)

您可以使用setdefault用一个空列表初始化每个值,然后附加另一个列表中的值

fruits = ["apple","apple","oranges","watermelon","apple"]
val = ["a","b","c","d","e"]
d={}

for k, v in zip(fruits, val):
    d.setdefault(k, []).append(v) 

print(d)
# {'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']}