简体   繁体   中英

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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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