简体   繁体   中英

Convert a list with duplicating keys into a dictionary and sum the values for each duplicating key

I am new to Python so I do apologize that my first question might not be asked clearly to achieve the right answer.

I thought if I converted a list with duplicating keys into a dictionary then I would be able to sum the values of each duplicating key. I have tried to search on Google and Stack Overflow but I actually still can't solve this problem.

Can anybody help, please? Thank you very much in advance and I truly appreciate your help.

list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]

My expected output is:

dict = {a: 10, b: 17, c: 7}

You can try this code:

list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]
l1 = [each.split(":") for each in list1]
d1 = {}
for each in l1:
    if each[0] not in d1:
        d1[each[0]] = int(each[1])
    else:
        d1[each[0]] += int(each[1])
d1 

Output: {'a': 10, 'b': 17, 'c': 7}

Explanation:

Step 1. Convert your given list to key-value pair by splitting each of the elements in your original list from : and store that in a list/tuple

Step 2. Initialize an empty dictionary

Step 3. Iterate through each key-value pair in the newly created list/tuple and store that in a dictionary. If the key doesn't exist, then add new key-value pair to dictionary or else just add the values to it's corresponding key.

A list does not have "keys" per say, rather it has elements. In your example, the elements them selves are a key value pair. To make the dictionary you want you have to do 3 things,

  1. Parse each element into its key value pair
  2. Handle duplicate values
  3. Add each pair to the dictionary.

the code should look like this

list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]
dict1={}#make an empty dictionary
for element in list1:
     key,value=element.split(':')#This splits your list elements into a tuple of (key,value)
     if key in dict1:#check if the key is in the dictionary
          dict1[key]+=int(value)#add to existing key
     else:
          dict1[key]=int(value)#initilize new key
print(dict1)

That code prints out {'a': 10, 'c': 7, 'b': 17}

You could use a defaultdict, iterate over each string and add the corresponding value after splitting it to a pair (key, value).

>>> from collections import defaultdict
>>> res = defaultdict(int)
>>> for el in list1:
...     k, v = el.split(':')
...     res[k]+=int(v)
... 
>>> res
defaultdict(<class 'int'>, {'a': 10, 'b': 17, 'c': 7})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM