-1

How could I add up the speed of these characters even if they don't all have the attribute speed? This is an example, there are many other attributes. The characters are picked randomly and grouped together:

character_1 = {'Money': .3, 'Strength': .25, 'Speed': .05}
character_2 = {'Money': .3, 'Age': 25, 'Speed': .7}
character_3 = {'Money': .3, 'Strength': .25, 'Power': 5}

How could I find out the combined speed, money, age etc of all these characters? (if age is not defined for others the right answer should be 25 years in total) thank you!!

Kiwipo17
  • 23
  • 4
  • What you actually want to do is merge your two dictionaries, and that's already been answered on [this SO question](https://stackoverflow.com/questions/10461531/merge-and-sum-of-two-dictionaries#10461916) (third line of the correct answer) – Arthur Spoon Dec 09 '17 at 13:18
  • Possible duplicate of [Merge and sum of two dictionaries](https://stackoverflow.com/questions/10461531/merge-and-sum-of-two-dictionaries) – Arthur Spoon Dec 09 '17 at 13:18
  • Actually you need to rethink your whole structure. You shouldn't create variable like that but create classes, use a database or nest them inside a dictionary. – Anton vBR Dec 09 '17 at 13:19

2 Answers2

0

Have a look at defaultdict . You could implement your characters as float defaultdicts, which gives them a 0.0 for any item that hasn't been set yet:

from collections import defaultdict

character = defaultdict(float)

So now any first item retrieval will initialize the value with zero if it hasn't been written before:

In [7]: character["Money"]
Out[7]: 0.0

In [8]: character["Speed"]
Out[8]: 0.0

This approach has its drawbacks for certain applications, though. Like when not all values in the dict are of numeric type, or have a different initial value. In this case, a class might be the only choice you've got, as @Anton vBR pointed out.

Jeronimo
  • 2,268
  • 2
  • 13
  • 28
0

You could loop through a list of the dicts and combine their values in a result dict like this:

character_1 = {'Money': .3, 'Strength': .25, 'Speed': .05}
character_2 = {'Money': .3, 'Age': 25, 'Speed': .7}
character_3 = {'Money': .3, 'Strength': .25, 'Power': 5}

dict_list = [character_1, character_2, character_3]

result = dict()

for d in dict_list:
    for k, v in d.items():
        if k in result:
            result[k] += v
        else:
            result[k] = v

print(result)

{'Money': 0.8999999999999999, 'Strength': 0.5, 'Speed': 0.75, 'Age': 25, 'Power': 5}
>>> 
srikavineehari
  • 2,502
  • 1
  • 11
  • 21