I am trying to create a dictionary from a parallel list, I am stuck because using zip and setdefault method doesn' allow more than 2 arguments. Can anybody assist
mainList=["A","B"]
mainListValue1=[1,22,3]
mainListValue2=["v1","v2"]
mainListValue3=["v4","v5"]
final_dict = {}
for mainList, mainListValue1, mainListValue2 in zip(mainList, mainListValue1, mainListValue2):
final_dict.setdefault(mainList, list()).append(mainListValue1)
print(final_dict)
Looking for following output
{'A':
1,
'v1',
'v4'
'B':
22,
'v2',
'v5'
}
First, note that your desired output is syntactically incorrect since the values of the dictionary are not coherently defined, ie you need the values to be packaged in something like a list. Otherwise, the Python interpreter would mistakenly believe that, for example, the 'v1'
element is not a value for 'A'
, but a start of a new key value.
With that in mind, here is a simple approach of looping through the lists to group elements into a value for a dictionary.
result = {}
for i, key in enumerate(mainList):
value = []
for lst in [mainListValue1, mainListValue2, mainListValue3]:
value.append(lst[i])
result[key] = value
print(result)
The result is the following output:
{'A': [1, 'v1', 'v4'], 'B': [22, 'v2', 'v5']}
I'd be happy to answer any additional questions you might have.
If the lists are parallel like that, you don't need setdefault()
, just use zip()
in conjunction with a dictionary comprehension like this:
#!/usr/bin/env python3
# https://stackoverflow.com/questions/60085285/append-key-values-to-dictionary-from-list
mainList = ["A","B"]
mainListValue1 = [1, 22, 3]
mainListValue2 = ["v1", "v2"]
mainListValue3 = ["v4", "v5"]
final_dict = {key: tuple(values) for key, *values
in zip(mainList, mainListValue1, mainListValue2, mainListValue3)}
print(final_dict) # -> {'A': (1, 'v1', 'v4'), 'B': (22, 'v2', 'v5')}
Note that the 3
in mainListValue1
gets ignored because the lists really aren't parallel.
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.