Assigning a list to a key of a dict
Chris Rebert
clp2 at rebertia.com
Thu May 14 11:58:04 EDT 2009
On Thu, May 14, 2009 at 8:45 AM, Wells <wells at submute.net> wrote:
> Why can't I do this?
>
> teams = { "SEA": "Seattle Mariners" }
> for team, name in teams.items():
> teams[team]["roster"] = ["player1", "player2"]
> I get an error:
>
> Traceback (most recent call last):
> File "./gamelogs.py", line 53, in <module>
> teams[team]["roster"] = ["player1", "player2"]
> TypeError: 'str' object does not support item assignment
teams - a dict of str to str
teams[team] - a string (specifically, "Seattle Mariners" in this case)
teams[team]["roster"] - um, you can't subscript a string by another
string; you can subscript it only by integer indices
> You can see that I am trying to make a key called "roster" for each
> team item in the dictionary, which is a list of players.
I'd say you need to restructure your data structure by introducing
another level of dictionaries:
teams = { "SEA": {"full_name":"Seattle Mariners"} }
for team, name in teams.items():
teams[team]["roster"] = ["player1", "player2"]
print teams
#output: {'SEA': {'full_name': 'Seattle Mariners', 'roster':
['player1', 'player2']}}
Of course, it would probably be nicer if you did this using objects
(e.g. define a Team class and have `teams` be a dict of str to Team.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list