从2个包含重复键的列表创建字典

时间:2018-03-14 00:31:08

标签: python python-2.7 list dictionary

虽然我已经看到了我的问题的版本,其中字典是从两个列表创建的(一个列表带有键,另一个带有相应的值),我想从列表中创建一个字典(包含键),和列表列表' (包含相应的值)。

我的代码示例是:

#-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)与它们各自的值配对。

相反,我不断得到以下结果:

{18: [13, 14, 15], 34: [4, 5, 6], 30: [10, 11, 12]}

此结果缺少我预期列表中的两个元素。

我希望能从这个论坛得到一些帮助。

2 个答案:

答案 0 :(得分:1)

如前所述,您无法获得所需的输出,因为字典键必须是唯一的。

如果您不想丢失数据,以下是两种选择。

元组列表

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]]})

答案 1 :(得分:0)

Keys need to be unique. 
You Have keys = [18, 34, 30, 30, 18]
Repeated keys 18 and 30 can not be used twice.
Try your script with unique keys and it works fine.
Keys read right to left. Notice you get the first key 18 
and the first key 30, but the second of each key is passed over 
相关问题