Advertisement
Advertisement


Creating a new dictionary in Python


Question

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?

2020/02/04
1
471
2/4/2020 5:03:23 PM

Accepted Answer

Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}
2015/11/08
684
11/8/2015 3:49:24 AM


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
2019/06/26

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

Will add the value in the python dictionary.

2017/03/27

d = dict()

or

d = {}

or

import types
d = types.DictType.__new__(types.DictType, (), {})
2011/12/08

So there 2 ways to create a dict :

  1. my_dict = dict()

  2. my_dict = {}

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

2018/08/31

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


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
2018/10/20

Source: https://stackoverflow.com/questions/8424942
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]