从2个具有重复键的列表中创建字典 [英] Creating a dictionary from 2 lists with duplicate keys
问题描述
尽管我看到过这样的问题,即从两个列表(一个带有键的列表,另一个带有对应的值)创建了一个字典,但我想从一个列表(包含键)创建一个字典,和列表列表"(包含相应的值).
Though I have seen versions of my issue whereby a dictionary was created from two lists (one list with the keys, and the other with the corresponding values), I want to create a dictionary from a list (containing the keys), and 'lists of list' (containing the corresponding values).
我的代码示例是:
#-Creating python dictionary from a list and lists of lists:
keys = [18, 34, 30, 30, 18]
values = [[7,8,9],[4,5,6],[1,2,3],[10,11,12],[13,14,15]]
print "This is example dictionary: "
print dictionary
我期望得到的结果是:
{18:[7,8,9],34:[4,5,6],30:[1,2,3],30:[10,11,12],18:[13,14,15]}
我不需要将重复的键(30、18)与它们各自的值配对.
I do not need the repeated keys (30, 18) to be paired up with their respective values.
相反,我不断得到以下结果:
Instead, I keep getting the following result:
{18: [13, 14, 15], 34: [4, 5, 6], 30: [10, 11, 12]}
此结果缺少了我期望列表中的两个元素.
This result is missing two of the elements from my expected list.
我希望这个论坛能对您有所帮助.
I am hoping to have some help from this forum.
推荐答案
如上所述,由于字典键必须唯一,因此无法实现所需的输出.
As already mentioned, your desired output is not possible as dictionary keys must be unique.
如果您不想丢失数据,则有以下两种选择.
Below are 2 alternatives if you do not want to lose data.
元组列表
res = [(i, j) for i, j in zip(keys, values)]
# [(18, [7, 8, 9]),
# (34, [4, 5, 6]),
# (30, [1, 2, 3]),
# (30, [10, 11, 12]),
# (18, [13, 14, 15])]
列表字典
from collections import defaultdict
res = defaultdict(list)
for i, j in zip(keys, values):
res[i].append(j)
# defaultdict(list,
# {18: [[7, 8, 9], [13, 14, 15]],
# 30: [[1, 2, 3], [10, 11, 12]],
# 34: [[4, 5, 6]]})
这篇关于从2个具有重复键的列表中创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!