Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method...

share|improve this question

9 Answers

up vote 370 down vote accepted
>>> d = {'key':'value'}
>>> print d
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print d
{'mynewkey': 'mynewvalue', 'key': 'value'}
share|improve this answer
4  
59  
Heh, now I feel kind of stupid. – lfaraone Jun 21 '09 at 22:15
147  
30,000 views makes it not so stupid – Yarin Jan 20 '12 at 19:56
11  
Does not (directly) work with nested dictionaries: test['x']['y']. test['x'] has to be initialized first. – koppor Jul 22 '12 at 10:35
5  
137000 now... – TakeS Feb 10 at 15:25
show 8 more comments
dictionary[key] = value
share|improve this answer
2  
You were the first. But unfortunately, not your answer on the top. – Vanuan Nov 4 '12 at 13:36

Yeah, it's pretty easy. Just do the following:

dict["key"] = "value"
share|improve this answer
1  
You've posted at the exactly same time. But unfortunately Paolo's answer has more votes. – Vanuan Nov 4 '12 at 13:39
>>> x = {1:2}
>>> print x
{1: 2}

>>> x.update({3:4})
>>> print x
{1: 2, 3: 4}
share|improve this answer
13  
That's the answer that should be in the top. – Vanuan Nov 3 '12 at 19:56
this applies for LISTS, not for dictionaries – reiven Nov 9 '12 at 19:59
1  
What do you mean? 'update' perfectly works for dictionaries. – Vanuan Nov 12 '12 at 20:21
2  
This answer was exactly what I was looking for. And re: "update" - docs.python.org/2/library/stdtypes.html#dict.update – Matt Dec 7 '12 at 22:05

I feel like consolidating info about python dictionary :

#### Making a dictionary ####
data = {}
# OR #
data = dict()

#### Initially adding values ####
data = {'a':1,'b':2,'c':3}
# OR #
data = dict(a=1, b=2, c=3)

#### Inserting/Updating value ####
data['a']=1  # updates if 'a' exists, else adds 'a'
# OR #
data.update({'a':1})
# OR #
data.update(dict(a=1))

#### Merging 2 dictionaries ####
data.update(data2)  # Where data2 is also a dict.

Feel free to add more !!

share|improve this answer
3  
Everything you need is in docs.python.org/library/stdtypes.html#mapping-types-dict – Michael Hoffman Dec 5 '11 at 6:12
3  
Though I read the docs I didn't notice dict.update until I saw an example here with dict.update({'a':1}). The docs list update as update([other]) which I guess never caught my eye. – Matt Dec 7 '12 at 22:08
1  
@Yugal Great job putting it all together :) Will definitely help beginners. – UGS Mar 27 at 10:10
data = {}
data['a'] = 'A'
data['b'] = 'B'

for key, value in data.iteritems():
    print "%s-%s" % (key, value)

results in

a-A
b-B
share|improve this answer
this answer is not much different than already provided – Vanuan Nov 3 '12 at 19:53
@Vanuan, the code is different though – daydreamer Nov 4 '12 at 7:54
stackoverflow isn't about the code, it's about solutions to problems. Your proposed solution (use index assignments) is exactly the same as already provided. – Vanuan Nov 4 '12 at 13:30

Also, if you want to add a dictionary within a dictionary you can do it this way...

Example: Add a new entry to your dictionary & sub dictionary

dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)

Output: {'new key': 'some value entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}

NOTE: Python requires that you first add a sub dictionary["dictionary_within_a_dictionary"] = {} before adding entries... this is kinda a bug with python.

Hope that helps...

V$H.

share|improve this answer
3  
this is as irrelevant to the question asked as most of the comments in php.net manual pages... – Erik Allik Jun 1 '12 at 21:05
3  
How is this a bug? – Kugel Aug 2 '12 at 19:05
2  
This is not a bug. – Vanuan Nov 3 '12 at 19:54
python inception – TMP Mar 11 at 10:09

The orthodox syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could do:

d.__setitem__(key, value)

In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the dictionary syntax. See http://www.diveintopython.net/object_oriented_framework/special_class_methods.html

share|improve this answer

you can create one

class myDict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        self[key] = value

## example

myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)

gives

>>> 
{'apples': 6, 'bananas': 3}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.