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 diction
d = dict()
or
d = {}
or
import types
d = types.DictType.__new__(types.DictType, (), {})
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
You can do this
x = {}
x['a'] = 1
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
Call dict
with no parameters
new_dict = dict()
or simply write
new_dict = {}
So there 2 ways to create a dict :
my_dict = dict()
my_dict = {}
But out of these two options {}
is efficient than dict()
plus its readable.
CHECK HERE