Assigning a list to a key of a dict

Diez B. Roggisch deets at nospam.web.de
Thu May 14 17:57:40 CEST 2009


Wells 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
> 
> 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.

This is not a list as key, it's a nested dictionary. There are several
approaches to this:

 - make your keys tuples, like this:

>>> teams[(team, "roster") = [...]

 - use setedfault:

>>> teams.setdefault(team, {})["roster"] = ['player1']

 - defaultdict

>>> from collections import *
>>> defaultdict
<type 'collections.defaultdict'>
>>> teams = defaultdict(dict)
>>> teams["team"]["roster"] = ["player1"]
>>> teams
defaultdict(<type 'dict'>, {'team': {'roster': ['player1']}})
>>>                                                   

Diez



More information about the Python-list mailing list