Chris Hanes
Chris Hanes

Reputation: 21

Append values to dictionary based on keys

I have a dictionary which contains multiple people's ID and an integer value (win total) like this:

{12345: 2, 23456: 10}

There are only 2 people in it currently for testing, but there will be a lot.

I have another dictionary in the same format with a different integer value (total games) like this:

{12345: 10, 23456: 20}

I need to create a third dictionary that stores win percentage like this (taking value from 1st dictionary and dividing by second dictionary):

{12345: .200, 23456: .500} *keeping raw percentage

-OR-

{12345: 20, 23456: 50} *multiply by 100 to get integer value (if that is only way I can do it)

This needs to be done for all players in the dictionary. There should be a matching pair in each dictionary for every person.

Can someone help? I have scoured these forums for days and can't find a good way to do it.

Upvotes: 1

Views: 138

Answers (3)

Drew
Drew

Reputation: 6638

The following will create a new dictionary with the percentages.

The cases where total games is zero or a people's entry is missing the games dictionary are handled by setting the percentage to 0.

wins={12345: 2, 23456: 10}
games={12345: 10, 23456: 20}

percentage={}
for key, value in wins.iteritems():
    try :
       percentage[key]=wins[key]*1.0/games[key]*1.0
    except KeyError :
       percentage[key]=0
    except ZeroDivisionError :
       percentage[key]=0

Upvotes: 0

C-F
C-F

Reputation: 1778

What about this:

{ key: wins[key]/games[key] for key in wins.keys()
                            if key in games and games[key]>0
}

where wins and games -- your source dictionaries. This will create result values only for keys presented in both dictionaries.

Upvotes: 1

Christian Ternus
Christian Ternus

Reputation: 8490

Why not compute the win percentage for each person on the fly? It'd be easier and more effective (and in keeping with good data storage principles) than keeping a third dictionary.

Something like:

def win_percentage(id):
    if id in total_games and id in num_wins and total_games[id] > 0:
        return num_wins[id] / float(total_games[id])
    else:
        return 0 # or raise an exception, whatever

Upvotes: 1

Related Questions