Dictionary of Dictionaries
Duncan Booth
duncan.booth at invalid.invalid
Mon Mar 5 10:33:25 EST 2007
"Bart Ogryczak" <B.Ogryczak at gmail.com> wrote:
> On Mar 5, 11:22 am, b... at yahoo.com wrote:
>> messagesReceived = dict.fromkeys(("one","two"), {})
>
> This creates two references to just *one* instance of empty
> dictionary.
> I'd do it like:
> messagesReceived = dict([(key, {}) for key in ("one","two")])
>
Alternatively use a defaultdict (Python 2.5) and you don't need to know the
keys in advance:
>>> from collections import defaultdict
>>> messagesReceived = defaultdict(dict)
>>> messagesReceived['one']['123'] = 11111
>>> messagesReceived['two']['121'] = 22222
>>> messagesReceived['two']['124'] = 43333
>>> messagesReceived
defaultdict(<type 'dict'>, {'two': {'121': 22222, '124': 43333}, 'one':
{'123': 11111}})
More information about the Python-list
mailing list