Take the 2-minute tour ×


share|improve this question
add comment

10 Answers

up vote 582 down vote accepted
>>> print d
{'key': 'value'}
>>> print d
share|improve this answer
Heh, now I feel kind of stupid. –  lfaraone Jun 21 '09 at 22:15
30,000 views makes it not so stupid –  Yarin Jan 20 '12 at 19:56
Does not (directly) work with nested dictionaries: test['x']['y']. test['x'] has to be initialized first. –  koppor Jul 22 '12 at 10:35
This can only mean one thing - more people are picking up Python. And that is something to be very happy about! –  Morgan Wilde Apr 9 at 18:47
show 2 more comments
>>> x = {1:2}
>>> print x
{1: 2}

>>> x.update({3:4})
>>> print x
{1: 2, 3: 4}
share|improve this answer
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
What do you mean? 'update' perfectly works for dictionaries. –  Vanuan Nov 12 '12 at 20:21
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
Is there something like this that returns the updated dictionary, instead of updating it in place? –  naught101 Oct 13 at 23:47
show 2 more comments

I feel like consolidating info about python dictionary :

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

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

#### Inserting/Updating value ####
data['a']=1  # updates if 'a' exists, else adds 'a'
# OR #
# OR #
# OR #
# OR #

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

Feel free to add more !!

share|improve this answer
Everything you need is in docs.python.org/library/stdtypes.html#mapping-types-dict –  Michael Hoffman Dec 5 '11 at 6:12
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
@Yugal Great job putting it all together :) Will definitely help beginners. –  UGS Mar 27 at 10:10
add comment

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

dict["key"] = "value"
share|improve this answer
You've posted at the exactly same time. But unfortunately Paolo's answer has more votes. –  Vanuan Nov 4 '12 at 13:39
add comment
dictionary[key] = value
share|improve this answer
You were the first. But unfortunately, not your answer on the top. –  Vanuan Nov 4 '12 at 13:36
add comment

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...


share|improve this answer
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
How is this a bug? –  Kugel Aug 2 '12 at 19:05
This is not a bug. –  Vanuan Nov 3 '12 at 19:54
python inception –  TMP Mar 11 at 10:09
add comment
data = {}
data['a'] = 'A'
data['b'] = 'B'

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

results in

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
add comment

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
"If your keyboard is missing the square bracket keys" you have bigger problems trying to write working code... –  Floris Jul 30 at 16:30
add comment

you can create one

class myDict(dict):

    def __init__(self):
        self = dict()

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

## example

myd = myDict()


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

This popular question addresses functional methods of merging dictionaries a and b.

Here are some of the more straightforward methods (tested in Python 3)...

c = dict( a, **b ) ## see also http://stackoverflow.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )

Note: The first method above only works if the keys in b are strings.

To add or modify a single element, the b dictionary would contain only that one element...

c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'

This is equivalent to...

def functional_dict_add( dictionary, key, value ):
   temp = dictionary.copy()
   temp[key] = value
   return temp

c = functional_dict_add( a, 'd', 'dog' )
share|improve this answer
Interesting comment about the first method from Python's BDFL (here). –  nobar Aug 17 at 23:09
add comment

protected by Marcin Sep 20 at 19:06

