Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary of dictionaries in Python?

From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4). I need to write a function that make a dictionary like this:

D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...}, 
   realName:{falseName:[positionOfMistake]...}...}

The function has to take a dictionary and a tuple like above, as arguments.

I was thinking something like this for a start:

def addToNameDictionary(d, tup):
    dictionary={}
    tup=previousFunction(string)
    for element in tup:
        if not dictionary.has_key(element[1]):
            dictionary.append(element[1])
    elif:
        if ...

But it is not working and I am kind of stucked here.

like image 596
Linus Svendsson Avatar asked Dec 18 '11 09:12

Linus Svendsson


1 Answers

If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:

def addNameToDictionary(d, tup):
    if tup[0] not in d:
        d[tup[0]] = {}
    d[tup[0]][tup[1]] = [tup[2]]
like image 83
aweis Avatar answered Oct 15 '22 00:10

aweis