Jignasha Royala
Jignasha Royala

Reputation: 1030

Using zip() Combining two lists into a dictionary with same keys in appand multipal values

I have two list and i try to combining in one dict

list1 = ['sys_time', 'sys_time', 'sys_time']
list2 = ['2018-03-16T11:00:00.000-07:00', '2018-03-12T00:00:00.000-07:00', '2018-03-14T00:00:00.000-07:00']

dict(zip(list1, list2))

output :

{'sys_time': '2018-03-14T00:00:00.000-07:00'}

how to I combining same keys in appand multipal values
like that :

{'sys_time': ['2018-03-16T11:00:00.000-07:00', 2018-03-12T00:00:00.000-07:00, '2018-03-14T00:00:00.000-07:00']} 

Upvotes: 0

Views: 46

Answers (2)

sam46
sam46

Reputation: 1271

because the keys are all the same (i.e sys_time)

list1 = ['sys_time1', 'sys_time2', 'sys_time3']
list2 = ['2018-03-16T11:00:00.000-07:00', '2018-03-12T00:00:00.000-07:00', '2018-03-14T00:00:00.000-07:00']

dict(zip(list1, list2))

but if you insist that they share the same key, one could associate keys with lists for values like so:

list1 = ['sys_time', 'sys_time', 'sys_time']
list2 = ['2018-03-16T11:00:00.000-07:00', '2018-03-12T00:00:00.000-07:00', '2018-03-14T00:00:00.000-07:00']
d = {}
for k,v in zip(list1, list2):
    d[k] = d.get(k, []) + [v]
print(d)

Upvotes: 1

iman_sh77
iman_sh77

Reputation: 77

I don't exactly understand what do you mean but considering combining two dict with each other like the output can be done like this code below:

x = ['sys_time', 'sys_time', 'sys_time']
y = ['2018-03-16T11:00:00.000-07:00', '2018-03-12T00:00:00.000-07:00', '2018-03-14T00:00:00.000-07:00']
dict = {x[0] : y[::]}
print(dict)

Upvotes: 1

Related Questions