2

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

6 Answers 6

1

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]}
1

Variation #1...

from collections import defaultdict
r = defaultdict(list)
for s, i in [item.split(',') for item in store1 + store2]: r[s].append(int(i))

Variation #2...

If I were planning on handling raw info from one or more stores, I might have a function and I would go for readability rather than compactness, and use type hints:

def raw_store_info_to_dict(all_store_raw_info: list[str]) -> defaultdict[str,list[int]]:
    all_stores_dict = defaultdict(list)
    for s, i in [item.split(',') for item in chain.from_iterable(all_store_raw_info)]:
        all_stores_dict[s].append(int(i))
    return all_stores_dict

store1=['mango,5', 'apple,10', 'banana,6']
store2=['mango,7', 'apple,8', 'banana,7']
store3=['mango,17', 'apple,18', 'banana,17']
store4=['grape,3', 'cider,2', 'banana,77']
store5=['mango,27', 'apple,28', 'banana,37']
print(raw_store_info_to_dict([store1, store2, store3, store4, store5]))

# Output:
# defaultdict(<class 'list'>, {'mango': [5, 7, 17, 27], 'apple': [10, 8, 18, 28], 'banana': [6, 7, 17, 77, 37], 'grape': [3], 'cider': [2]})
0

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

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

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

Use dict.setdefault:

d = {}
for i in store1 + store2:
  key,value = i.split(',')
  d.setdefault(key, []).append(int(value)) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.