Home > Software design >  convert list with same values to dict - smart zip (python)
convert list with same values to dict - smart zip (python)

Time:10-04

I have the list:

['apples', 400, 'sweets', 300, 'apples', 750]

After applying function:

def Convert(a):
    it = iter(a)
    res_dct = dict(zip(it, it))
    return res_dct

I get the result: {'apples': 750, 'sweets': 300}

But I need: {'apples': 1150, 'sweets': 300}

CodePudding user response:

You can use .get() from dictionary if key exists you can sum with money if key not exist you can sum 0 with money like below.

Try this:

lst = ['apples', 400, 'sweets', 300, 'apples', 750]
    
dct = {}
for frt, mny in zip(lst[::2], lst[1::2]):
    dct[frt] = dct.get(frt, 0)   mny
    
print(dct)

Output:

{'apples': 1150, 'sweets': 300}

CodePudding user response:

Alternatively, you can also try to use the collections defaultdict and Counter to achieve the same results. This is just to follow your original code and flow:

from collections import Counter, defaultdict

# data = ['apples', 400, 'sweets', 300, 'apples', 750]


def convert(A):
    result = defaultdict(Counter)
    it = iter(A)
    
    for fruit, count in zip(it, it):
        if fruit not in result:
            result[fruit]  = count
        else:
            result[fruit]  = count
    
    return result
    

Running it:

print(convert(data))

# defaultdict(<class 'collections.Counter'>, {'apples': 1150, 'sweets': 300})
  • Related