544

I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . ..

How do I create a new empty dictionary in Python?

Georgy
  • 12,464
  • 7
  • 65
  • 73
leora
  • 188,729
  • 360
  • 878
  • 1,366

8 Answers8

759

Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}
poolie
  • 9,289
  • 1
  • 47
  • 74
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90
  • 50
    Is there any difference between dict() and {}? Or do people just prefer one over the other? – Matt Mar 02 '12 at 17:13
  • 57
    @ Matt Apparently CPython 2.7 dict() is slower (6 times slower?), See: http://doughellmann.com/2012/11/the-performance-impact-of-using-dict-instead-of-in-cpython-2-7-2.html In any case I am starting to prefer the constructor syntax anyways since I find it easier to type and move code between dicts and function calls. – David Wheaton Mar 05 '13 at 20:53
  • 1
    @DavidWheaton Thanks for pointing this out! Personally, I find `new_dict = dict()` slightly more readable, nonetheless if there is such a big difference in regards to performance... Would go for performance! ;) (For those who are confused about Python and Cphython see: [here](http://stackoverflow.com/a/17130986/4773274)) – holzkohlengrill Jul 18 '16 at 07:25
  • 22
    I confirm it's 3 times faster to use { } than dict() in python 3.x – Alex Azazel Jan 03 '17 at 19:09
  • 14
    Yeah, I get about 4 times faster in python 3.6 for `{}` over `dict()` and 5 times for `[]` over `list()`. – Michael Hall Dec 19 '17 at 14:40
  • 26
    In the vast majority of cases, it doesn't matter if it takes six times longer, since that's still an unnoticeably small amount of time. – hypehuman Jan 10 '19 at 20:43
  • ```{}``` is faster because it cant be overwritten but ```dict()``` can be so there are some extra checks and lookups – Carter Cole Oct 18 '22 at 14:45
269

You can do this

x = {}
x['a'] = 1
TJD
  • 11,800
  • 1
  • 26
  • 34
35

Knowing how to write a preset dictionary is useful to know as well:

cmap =  {'US':'USA','GB':'Great Britain'}

# Explicitly:
# -----------
def cxlate(country):
    try:
        ret = cmap[country]
    except KeyError:
        ret = '?'
    return ret

present = 'US' # this one is in the dict
missing = 'RU' # this one is not

print cxlate(present) # == USA
print cxlate(missing) # == ?

# or, much more simply as suggested below:

print cmap.get(present,'?') # == USA
print cmap.get(missing,'?') # == ?

# with country codes, you might prefer to return the original on failure:

print cmap.get(present,present) # == USA
print cmap.get(missing,missing) # == RU
fyngyrz
  • 2,458
  • 2
  • 36
  • 43
  • 5
    Good point! But I think the bit with `cxlate` makes your answer seem too complicates. I'd just keep the initialization part. (`cxlate` itself is too complicated. You could just `return cmap.get(country, '?')`.) – Daniel Darabos Apr 11 '15 at 20:14
  • 1
    Consider using https://docs.python.org/2/library/collections.html#collections.defaultdict instead of writing a translate function or using .get() everywhere. – Sparr Jun 30 '15 at 16:20
  • 2
    Perhaps I would, except that the documentation is absolutely opaque to me -- it's terrible. I have no idea what they're telling me to do, or why I should do it. And .get() seems to do exactly the right thing -- plus it's extremely flexible. I'm sure its a lack of understanding on my part. With that in mind, my questions are: why bother? What is saved here, easier here, faster here, etc.? Benefit is exactly what? – fyngyrz Jul 01 '15 at 12:01
  • This appears useful, but a bit complicated for beginners – psychonomics Jan 31 '20 at 11:07
25
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}

Will add the value in the python dictionary.

Atul Arvind
  • 16,054
  • 6
  • 50
  • 58
20
d = dict()

or

d = {}

or

import types
d = types.DictType.__new__(types.DictType, (), {})
ukessi
  • 1,381
  • 1
  • 10
  • 15
  • What is the difference between `types.DictType.__new__(types.DictType, (), {})` and just `{}` –  Sep 03 '19 at 07:37
  • 5
    For anyone reading this: the last "solution" is a bit of a joke - you _can_ use it (in python 2.x at least - won't work in py3k), but no one in it's own mind would ever want to do so ;-) – bruno desthuilliers Sep 03 '19 at 07:58
13

So there 2 ways to create a dict :

  1. my_dict = dict()

  2. my_dict = {}

But out of these two options {} is more efficient than dict() plus its readable. CHECK HERE

Wolf
  • 9,679
  • 7
  • 62
  • 108
Vishvajit Pathak
  • 3,351
  • 1
  • 21
  • 16
  • 1
    Why are you referring to python2.7? (in a quite old article: 2012-11-12, "The Performance Impact of Using dict() Instead of {} in CPython 2.7") – Wolf Jan 14 '21 at 14:11
  • (7 yrs later) performances did not changed even in python 3.x.x you can see it running a %timeit my_dict = {} vs %timeit my_dict = dict() – Carlo Sep 16 '21 at 10:20
7
>>> dict.fromkeys(['a','b','c'],[1,2,3])


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
sudhir tataraju
  • 1,159
  • 1
  • 14
  • 30
0

I do not have enough reputation yet to be able comment, so I share this as an answer.

The link shared by @David Wheaton in his comment to the accepted answer is no longer valid as Doug Hellmann has migrated his site (source: https://doughellmann.com/posts/wordpress-to-hugo/).

Here is the updated link about "The Performance Impact of Using dict() Instead of {} in CPython 2.7": https://doughellmann.com/posts/the-performance-impact-of-using-dict-instead-of-in-cpython-2-7-2/

julien ergan
  • 109
  • 1
  • 5