Skip to content Skip to sidebar Skip to footer

How To Append To A Dictionary Of Dictionaries

I'm trying to create a dictionary of dictionaries like this: food = {'Broccoli': {'Taste': 'Bad', 'Smell': 'Bad'}, 'Strawberry': {'Taste': 'Good', 'Smell': 'Good'}} But I

Solution 1:

In order to make solution position independent you can make use of dict1.update(dict2). This simply merges dict2 with dict1.

In our case since we have dict of dict, we can use dict['key'] as dict1 and simply add any additional key,value pair as dict2.

Here is an example.

food = {"Broccoli": {"Taste": "Bad", "Smell": "Bad"}, 
        "Strawberry": {"Taste": "Good", "Smell": "Good"}}

addthis = {'foo':'bar'}

Suppose you want to add addthis dict to food['strawberry'] , we can simply use,

food["Strawberry"].update(addthis)

Getting result:

>>> food
{'Strawberry': {'Taste': 'Good', 'foo': 'bar', 'Smell': 'Good'},'Broccoli': {'Taste': 'Bad', 'Smell': 'Bad'}}
>>>  

Solution 2:

Assuming that column 0 is what you wish to use as your key, and you do wish to build a dictionary of dictionaries, then its:

detail_names = [col[0] for col in result.description[1:]]
foodList = {row[0]: dict(zip(detail_names, row[1:]))
            for row in result}

Generalising, if column k is your identity then its:

foodList = {row[k]: {col[0]: row[i]
                     for i, col in enumerate(result.description) if i != k}
            for row in result}

(Here each sub dictionary is all columns other than column k)


Solution 3:

addMe = {str(food[1]):dict(zip(nutCol[2:],food[2:]))}

zip will take two (or more) lists of items and pair the elements, then you can pass the result to dict to turn the pairs into a dictionary.


Post a Comment for "How To Append To A Dictionary Of Dictionaries"