python中字典的几种定义方式

python中字典的定义方式有很多种,下面给出其中一些方式: 

# 方式1
>>> d = dict(name='Bob', age=20, score=88)
>>> print(d)
{'name': 'Bob', 'age': 20, 'score': 88}

>>> d = dict("name"='Bob', "age"=20, "score"=88)
SyntaxError: keyword can't be an expression

>>>d = dict("name":'Bob', "age":20, "score":88)
SyntaxError: invalid syntax

# 方式2
>>> d = {"name":'Bob', "age":20, "score":88}
>>> print(d)
{'name': 'Bob', 'age': 20, 'score': 88}

>>> d = {"name"='Bob', "age"=20, "score"=88}
SyntaxError: invalid syntax

>>> d = {name:'Bob', age:20, score:88}
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    d = {name:'Bob', age:20, score:88}
NameError: name 'name' is not defined

# 方式3
>>> d = dict([["name", "zh"], ["age", "18"]])
>>> print(d)
{'name': 'zh', 'age': '18'}

# 方式4
>>> d = dict([("name", "zh"), ("age", "18")])
>>> print(d)
{'name': 'zh', 'age': '18'}







作者:David-lcw
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/david-lcw/p/10051275.html