Is there a way to access keys with the same name from multiple dictionary?

Viewed 388

I have multiple dictionaries with a predictable name. Each dictionary contains 3 elements. How am I able to extract a particular key from each dictionary and find the total value?

player_A = {
   "kills": 15
   "death": 3
   "kda": 5
}

player_B = {
   "kills": 20
   "death": 4
   "kda": 5
}
:
player_ZA = {
   "kills": 35
   "death": 7
   "kda": 5
}

Let's say I wanted to find the total kills of all players. How should i go about accessing all the keys named 'kill' in the dictionaries and find the total sum of these keys?

ie. Expected output is something along the lines of:

sum(15 + 20 + ... + 35)
4 Answers
player_a = {"kills": 15, "death": 3, "kda": 5}
player_b = {"kills": 20, "death": 4, "kda": 5}
player_c = {"kills": 35, "death": 7, "kda": 5}

players = [player_a, player_b, player_c]

total_kills = sum(player["kills"] for player in players)

Try this one:

player_A = {"kills": 15, "death": 3, "kda": 5}

player_B = {"kills": 20, "death": 4, "kda": 5}

player_ZA = {"kills": 35, "death": 7, "kda": 5}


def f(x):
    result = 0
    for key, value in x.items():
        if key.startswith("player"):
            result += value["kills"]
    return result


print(f(globals()))

Or this one:

player_A = {"kills": 15, "death": 3, "kda": 5 }

player_B = { "kills": 20, "death": 4, "kda": 5 }

player_ZA = { "kills": 35, "death": 7, "kda": 5 }


def f(x):
    return sum(value["kills"] for key, value in x.items() if key.startswith("player"))


print(f(globals()))

You can also do this:-

player_a = {"kills": 15, "death": 3, "kda": 5}
player_b = {"kills": 20, "death": 4, "kda": 5}
player_c = {"kills": 35, "death": 7, "kda": 5}
player_d = {'death':5}  # If dictionary does not contains 'kills' key.

players = [player_a , player_b , player_c, player_d]

l = []
for player in players:
    try:
        l.append(player['kills'])

    except Exception as e:
        continue
print(f"Total kills are {sum(l)}") 

Output

Total kills are 70

I hope you learn something new.

Here is another way (functional programming) to sum the "kills" values:

player_A = {"kills": 15, "death": 3, "kda": 5}

player_B = {"kills": 20, "death": 4, "kda": 5}

player_ZA = {"kills": 35, "death": 7, "kda": 5}


f = lambda x: sum(map(lambda j: x[j]["kills"], filter(lambda i: i.startswith("player"), x)))


print(f(globals()))
Related