Feed on
Posts
Comments

to create a double dictionary in python, the following won’t work:

>>> x = dict()
>>> x[1][1] = “foo”

instead, you need only one set of brackets:

>>> x = dict()
>>> x = [1,1] = “foo”


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

4 Responses to “create a double dictionary in python”

  1. on 16 Oct 2008 at 6:50 pm Elmer

    That’s actually not a nested dictionary you’re making there, you’re just using a tuple for its key:

    >>> d = {}
    >>> d['key'] = ‘some value’
    >>> d['a','b'] = ‘nested?’
    >>> d
    {(‘a’, ‘b’): ‘nested?’, ‘key’: ‘some value’}

    If you want a dictionary inside a dictionary (which it seems is what you want), go about it like this:

    >>> d['nest'] = {}
    >>> d['nest']['key'] = ‘value’
    >>> d
    {(‘a’, ‘b’): ‘nested?’, ‘nest’: {‘key’: ‘value’}, ‘key’: ‘some value’}

    or, if you want to assign to a nested dictionary you’re not sure already exists:

    >>> d.setdefault(‘new key’, {})['level2'] = ‘auto_nest’
    >>> d
    {(‘a’, ‘b’): ‘nested?’, ‘new key’: {‘level2′: ‘auto_nest’}, ‘nest’: {‘key’: ‘value’}, ‘key’: ‘some value’}

  2. on 03 Sep 2010 at 5:02 am Henrik Karlsson

    Just because I searched like an idiot after adding as many dictionarys inside dictionarys as I wanted depending on how many objects was inside a List I’ll add that here since it’s fairly relevant. Hopefully someone will find it through google and will have some use of it =D

    This post was very helpful though in how I could achieve it.

    this is how it is done:

    for list in listOfPasses:

    completeList[i] = {listOfPasses[i] : {} }
    completeList[listOfPasses[i]] = {“key” : “value”}
    i = i + 1

    pretty simplified though, I also use list to set values and so on in passes, since this is done within maya to set attributes to renderman passes outside maya through a .conf file.

  3. on 05 Nov 2011 at 6:55 pm Shane O

    Here was an easy way that i done it.

    list1 = []

    dict1 = {}
    dict1["key1"] = “value1″

    list1.append(dict1)

    dict2 = {}
    dict2["key2"] = “value2″

    list1.append(dict2)

    # Retrieve the Dictionary’s #
    listdict1 = list1[0]
    listdict2 = list1[1]

    print “This is the first dict” , listdict1
    print “Here is the second dict” , listdict2

    P.S. I found this site trying to figure out how to do it. Haha

  4. on 13 Dec 2012 at 5:16 am WIlmer T

    Why not simply something like
    queue_params = ['queue','sndQueueSize','outQueueSize']
    countable_params = ['hangUps','estRetries']
    keys = queue_params + countable_params
    p_init = { ‘msg’:”", ‘count’: { ‘old’:0,’new’:0 } }
    params = dict.fromkeys(keys, p_init)

    Or am I barking up the wrong tree? ;)

Did I get this wrong? Let me know!

Trackback URI | Comments RSS