用Python创建新字典

问题:用Python创建新字典

我想用Python建立字典。但是,我看到的所有示例都是从列表中实例化字典等。..

如何在Python中创建一个新的空字典?

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?


回答 0

dict无参数调用

new_dict = dict()

或简单地写

new_dict = {}

Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}

回答 1

你可以这样做

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

You can do this

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

回答 2

知道如何编写预设字典对了解也很有帮助:

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

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

回答 3

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

将值添加到python字典中。

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

Will add the value in the python dictionary.


回答 4

d = dict()

要么

d = {}

要么

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

or

d = {}

or

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

回答 5

因此,有两种创建字典的方法:

  1. my_dict = dict()

  2. my_dict = {}

但是,在这两个选项{}中,比dict()加上其可读性更有效。 在这里检查

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


回答 6

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


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


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