Creating a new dictionary in Python

PythonDictionary

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}

Solution 2 - Python

You can do this

x = {}
x['a'] = 1

Solution 3 - Python

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

Solution 4 - Python

>>> dict(a=2,b=4)
{'a': 2, 'b': 4}

Will add the value in the python dictionary.

Solution 5 - Python

d = dict()

or

d = {}

or

import types
d = types.DictType.__new__(types.DictType, (), {})

Solution 6 - Python

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

Solution 7 - Python

>>> dict.fromkeys(['a','b','c'],[1,2,3])


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

Solution 8 - Python

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - PythonJan VorcakView Answer on Stackoverflow
Solution 2 - PythonTJDView Answer on Stackoverflow
Solution 3 - PythonfyngyrzView Answer on Stackoverflow
Solution 4 - PythonAtul ArvindView Answer on Stackoverflow
Solution 5 - PythonukessiView Answer on Stackoverflow
Solution 6 - PythonVishvajit PathakView Answer on Stackoverflow
Solution 7 - Pythonsudhir tatarajuView Answer on Stackoverflow
Solution 8 - Pythonjulien erganView Answer on Stackoverflow