I am creating a dictionary using two lists that have multiple values, and without using zip
.
If I have two lists like this:
store1=['mango,5', 'apple,10', 'banana,6']
store2=['mango,7', 'apple,8', 'banana,7']
How do I create a dictionary like this:
dic={'mango':[5,7],'apple':[10,8],'banana':[6,7]}
CodePudding user response:
You can do this with dict.setdefault
,
In [2]: d = {}
...: for i in store1 store2:
...: key,value = i.split(',')
...: d.setdefault(key, []).append(int(value))
In [3]: d
Out[3]: {'mango': [5, 7], 'apple': [10, 8], 'banana': [6, 7]}
CodePudding user response:
You could try using 2 separate for-loops to add them to the dictionary
store1 = ['mango,5', 'apple,10', 'banana,6']
store2 = ['mango,7', 'apple,8', 'banana,7']
d = {}
for i in store1:
a, b = i.split(',')
if a not in d:
d[a] = []
d[a].append(int(b))
for i in store2:
a, b = i.split(',')
if a not in d:
d[a] = []
d[a].append(int(b))
print(d)
Or Use a nested for-loop
store1 = ['mango,5', 'apple,10', 'banana,6']
store2 = ['mango,7', 'apple,8', 'banana,7']
d = {}
for i in [store1,store2]:
for j in i:
a, b = j.split(',')
if a not in d:
d[a] = []
d[a].append(int(b))
print(d)
CodePudding user response:
Adding another solution without using zip
is to just concatenate the given lists thus creating one big list to iterate through:
d={}
for store in (store1 store2):
key, val = store.split(",")
if key not in d:
d[key] = []
d[key].append(int(val))
CodePudding user response:
Without zip
, ok.
st1 = sorted([ e.split(',') for e in store1 ])
st2 = sorted([ e.split(',') for e in store2 ])
dic = { st1[i][0]: [ st1[i][1], st2[i][1] ] for i in range(len(st1))}
Without zip
, if the lists are not in good form. i.e. not in the correct order, or the keys may not exist on both lists, etc. This solution has a better compatibility.
dic = { k:v for [k,v] in [ e.split(',') for e in store1 ] }
for [k,v] in [ e.split(',') for e in store2 ]:
if k in dic: dic[k].append(v)
else: dic[k]=[v]
With zip
One line:
dic = { kv1.split(',')[0]: [kv1.split(',')[1], kv2.split(',')[1]] for kv1,kv2 in zip(store1,store2) }
With zip
, another solution with a better runtime performance if your data is big
st1 = [ e.split(',') for e in store1 ]
st2 = [ e.split(',') for e in store2 ]
dic = { kv1[0]: [ kv1[1], kv2[1] ] for kv1,kv2 in zip( st1, st2 ) }