Zanam - 6 months ago 8

Python Question

I have two lists:

`L1 = ['A','B','A','C','A']`

L2 = [1, 4, 6, 1, 3]

I want to create a dictionary which has the following output:

`DictOutSum = {'A':10, 'B':4, 'C':1}`

DictOutCount = {'A':3, 'B':1, 'C':1}

i.e. Lists L1 and L2 both have same number of elements and the elements in them corresponds one to one. I want to find sum of all numbers in L2 for each unique element in L1 and make a dictionary out of it(DictOutSum). I also want to create another dictionary which stores the counts of number of unique elements of L1(DictOutCount).

I don't even have an idea where to start for this other than to use a for loop.

Answer

Pure python implementation:

```
>>> dict_sum = dict.fromkeys(L1, 0)
>>> dict_count = dict.fromkeys(L1, 0)
>>> for k,n in zip(L1, L2):
... dict_sum[k] += n
... dict_count[k] += 1
...
>>> dict_sum
{'A': 10, 'B': 4, 'C': 1}
>>> dict_count
{'A': 3, 'B': 1, 'C': 1}
```

Fancy one-liner implementations:

```
>>> from collections import Counter
>>> Counter(L1) # dict_count
Counter({'A': 3, 'B': 1, 'C': 1})
>>> sum((Counter({k:v}) for k,v in zip(L1, L2)), Counter()) # dict_sum
Counter({'A': 10, 'B': 4, 'C': 1})
```