请分析一下哪个可读性好, a) dict(fast=256*1000, food=3*10) b) dict([ ('fast', 256*1000), ('food', 3*10) ])

2018-12-11 15:47:04 +08:00
 northisland

比较菜,今天自己打一遍代码前,不知道 dict 还能做这种类似 **kwargs 的初始化。

请问 a, b 这 2 种写法,


好吧,还是我知识面比较狭窄,确实应该抽空再看看 docs.python.org


https://docs.python.org/3.1/tutorial/datastructures.html

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}
1674 次点击
所在节点    Python
10 条回复
holajamc
2018-12-11 15:54:33 +08:00
个人喜欢 A 写法~
northisland
2018-12-11 15:55:20 +08:00
我现在的答案:

1. 看过教程,觉得都可以了,可读性相同
2. 这种常见的赋值方法,不存在 preferably only one 方法
est
2018-12-11 16:07:15 +08:00
用 dict() 生成动态的 。用 { } 定义静态的。
xpresslink
2018-12-11 16:41:03 +08:00
你这两种写法都不好,如果定义个常量的字典应该直接写成
d={'sape': 4139, 'jack': 4098, 'guido': 4127}
这样性能和可读性都好。
SeaRecluse
2018-12-11 16:49:43 +08:00
d = {}
d.update{}
datou
2018-12-11 17:04:41 +08:00
楼主为啥看 python3.1 的文档?

应该看 python3.7.1 的文档呀
northisland
2018-12-11 17:34:29 +08:00
fngtz
2018-12-12 04:31:13 +08:00
第一种直接就生成 dict 对象了。第二种,先生成两个 tuple,再组成一个 list,再 iterate 这个 list 才生成 dict 对象啊。
northisland
2018-12-21 17:39:11 +08:00
@fngtz
@holajamc

```
key = ‘ 1234 ’
d = dict(key=key)
print(d)
>>> {‘ key ’, ‘ 1234 ’}
```
这句简直是鬼畜啊,dict(key=key)
holajamc
2018-12-21 17:41:29 +08:00
@northisland 并不会啊,因为第一个 key 是参数名,第二个 key 是参数值呀

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/516541

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX