Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically add key to Python dict

Tags:

python

I want to automatically add keys to a Python dictionary if they don't exist already. For example,

a = "a"
b = "b"
c = "c"

dict = {}
dict[a][b] = c # doesn't work because dict[a] doesn't exist

How do I automatically create keys if they don't exist?

like image 931
egidra Avatar asked Oct 31 '12 04:10

egidra


People also ask

How do you assign a key to a dictionary in Python?

You can add key to dictionary in python using mydict["newkey"] = "newValue" method. Dictionaries are changeable, ordered, and don't allow duplicate keys. However, different keys can have the same value.

How do you add values to an existing dictionary key without replacing the previous value?

In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value. By using the setdefault() method, you can add items with new values only for new keys without changing the values for existing keys.

Can you append to a dictionary in Python?

We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.


2 Answers

Use a collections.defaultdict:

def recursively_default_dict():
    return collections.defaultdict(recursively_default_dict)

my_dict = recursively_default_dict()
my_dict['a']['b'] = 'c'
like image 134
icktoofay Avatar answered Sep 21 '22 08:09

icktoofay


from collections import defaultdict
d = defaultdict(dict)
d['a']['b'] = 'c'

Also, please be careful when using dict - it has a meaning in python: https://docs.python.org/2/library/stdtypes.html#dict

like image 34
Jean Spector Avatar answered Sep 18 '22 08:09

Jean Spector