Can a value in a Python Dictionary have two values?
For a test program I'm making a simple model of the NFL. I'd like to assign a record (wins and losses) to a team as a value in a dictionary? Is that possible?
For example:
af开发者_运维百科cNorth = ["Baltimore Ravens", "Pittsburgh Steelers", "Cleveland Browns", "Cincinatti Bengals"]
If the Ravens had 13 wins and 3 loses, can the dictionary account for both of those values? If so, how?
sure, just make the value a list or tuple:
afc = {'Baltimore Ravens': (10,3), 'Pb Steelers': (3,4)}
If it gets more complicated, you might want to make a more complicated structure than a tuple - for example if you like dictionaries, you can put a dictionary in your dictionary so you can dictionary while you dictionary.
afc = {'Baltimore Ravens': {'wins':10,'losses': 3}, 'Pb Steelers': {'wins': 3,'losses': 4}}
But eventually you might want to move up to classes...
The values in the dictionary can be tuples or, maybe better in this case, lists:
d = {"Baltimore Ravens": [13, 3]}
d["Baltimore Ravens"][0] += 1
print d
# {"Baltimore Ravens": [14, 3]}
Well, you can use a tuple (or a list):
records = {}
records["Baltimore Ravens"] = (13, 3)
Or you could be fancy and make a Record
class with Record.wins
and record.losses
, but that's probably overkill.
(As another answer points out, using a list means that you can do arithmetic on the values, which might be useful.)
精彩评论