简体   繁体   English

Python:创建列表列表作为字典值

[英]Python: Create list of lists as dictionary values

I have two lists that I would like to associate by index as key value pairs in a dictionary. 我有两个列表,希望通过索引将它们作为字典中的键值对关联。 The key list has multiple identical elements. 密钥列表具有多个相同的元素。 I would like the all elements in the value list to be paired as a list of list. 我希望将值列表中的所有元素配对为一个列表列表。 I am using the list.append() method, but this is not giving me the desired output. 我正在使用list.append()方法,但这没有给我想要的输出。 Any recommendations on the code or should I be looking at the problem in a different way? 有关代码的任何建议,还是应该以其他方式查看问题?

list1 = ['a', 'b', 'b', 'b', 'c']
list2 = [['1', '2', '3'], ['4', '5', '6'], [ '7', '8', '9'], ['10', '11', '12'], ['13', '14', '15']]

combo = {}
for i in range(len(list1)):
    if list1[i] in combo:
        combo[list1[i]].append(list2[i])
    else:
        combo[list1[i]] = list2[i]

Current output: 电流输出:

{'a': ['1', '2', '3'], 'b': ['4', '5', '6', [ '7', '8', '9'], ['10', '11', '12']], 'c': ['13', '14', 15']}

Desired output: 所需的输出:

{'a': [['1', '2', '3']], 'b': [['4', '5', '6'], [ '7', '8', '9'], ['10', '11', '12']], 'c': [['13', '14', 15']]}

Use a defaultdict , with the empty list an starting value 使用defaultdict ,空列表为起始值

 result = defaultdict(list)

 for key, value in zip(list1, list2):
      result[key].append(value)

Try out this code. 试试这个代码。 It's working when I tried with the same input that you have given. 当我尝试使用您提供的相同输入时,它就起作用了。

#Input
list1= ['a','b', 'b','b', 'c']
list2 = [['1', '2', '3'], ['4', '5', '6'], [ '7', '8', '9'], ['10','11','12'], ['13', '14', '15']]

combo= {}
for index, value in enumerate(list1):
    if value in combo.keys():
        combo[value].append(list2[i])
    else:
        combo[value]= []
        combo.append(list2[i])
#output
print(combo)
{'a': [['1', '2', '3']],'b': [['4', '5', '6'], ['7', '8', '9'], ['10', '11', '12']], 'c': [['13', '14', '15']]}

如果您希望获得更Python化的响应,还可以使用dict comprension:

output = {key: [value] for key, value in zip(list1, list2)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM