关于列表:在python中创建新dict

Creating a new dict in Python

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

如何在python中创建新的空字典?


不带参数调用dict

1
new_dict = dict()

或者简单地写

1
new_dict = {}


你可以做到这一点

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


了解如何编写预设字典也很有用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cmap =  {'US':'USA','GB':'Great Britain'}

def cxlate(country):
    try:
        ret = cmap[country]
    except:
        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


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

将在python字典中添加值。


1
d = dict()

1
d = {}

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

因此,有两种方法可以创建dict:

  • my_dict = dict()

  • my_dict = {}

  • 但在这两个选项中,{}dict()加上它的可读性更有效率。这里检查


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


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