Answer the question
In order to leave comments, you need to log in
How to combine 2 lists into 1 dictionary in Python?
There are 2 lists:
ID_Masterok = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ID_Master = ['Master ID', '654', '2425', '654', ' 654', '—', '—', '—', '—', '—', '—'] Executing
:
ID_Mastework = dict(zip(ID_Master, ID_Masterok))
Returns: {'Master ID': 0, '654': 4, '2425': 2 , '—': 10}
I want something like this: {'Master ID': 0, '654': [1, 3, 4], '2425': 2, '—': [7, 8, 9, 10]}
Answer the question
In order to leave comments, you need to log in
def mastework(id_key, id_value):
id_join = {}
for k, v in zip(id_key, id_value):
id_join[k] = id_join.get(k, []) + [v]
return {k:v if len(v) > 1 else v[0] for k, v in id_join.items()}
ID_Masterok = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ID_Master = ['Интендификатор мастера', '654', '2425', '654', '654', '—', '—', '—', '—', '—', '—']
ID_Mastework = mastework(ID_Master, ID_Masterok)
print(ID_Mastework)
In [55]:
{'Интендификатор мастера': 0, '654': [1, 3, 4], '2425': 2, '—': [5, 6, 7, 8, 9, 10]}
I did not see such a function, it's easier to write by hand:
def zzip(ID_Master,ID_Masterok):
result = {}
for i in ID_Masterok:
if ID_Master[i] in result:
if isinstance(result[ID_Master[i]],list):
result[ID_Master[i]].append(i)
else:
result[ID_Master[i]] = [result[ID_Master[i]],i]
else:
result[ID_Master[i]] = i
return result
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question