Python dictionary; sum values of the same keys

后端 未结 2 532
情话喂你
情话喂你 2021-01-24 06:50

It might be simple but im just a beginner. If i have this dictionary;

ds = {\"ABab\": 6.25, \"aBab\": 6.25, \"Abab\": 6.25, \"abab\": 6.25, \"ABab\": 6.25, \"aBa         


        
2条回答
  •  我在风中等你
    2021-01-24 07:20

    As noted already, you can't store this data in a dictionary. You could store it in some other form such as a list of tuples.

    ds = [("ABab", 6.25), ("aBab", 6.25), ("Abab", 6.25), ("abab", 6.25),
          ("ABab", 6.25), ("aBab", 6.25), ("Abab", 6.25), ("abab", 6.25),
          ("ABab", 6.25), ("aBab", 6.25), ("Abab", 6.25), ("abab", 6.25),
          ("ABab", 6.25), ("aBab", 6.25), ("Abab", 6.25), ("abab", 6.25)]
    

    Then you can make a dictionary of the totals by first finding the unique keys and then summing the values of the tuples which have that key as their first value.

    keys = set(k for k, _ in ds)
    totals = {unique_key: sum(v for k, v in ds if k==unique_key) 
        for unique_key in keys}
    

    Or another way (probably better)

    totals = {}
    for key, value in ds:
        totals[key] = totals.get(key, 0) + value
    

提交回复
热议问题