如何可以简单地嵌套生成一个字典

2014-01-21 17:16:42 +08:00
 P9
希望能做到:
In [24]: c =dict()
In [24]: c.people.name = 'roy'

In [25]: c
Out[25]: {'people': {'name': 'roy'}}

你的方案是?

附上我的:http://scriptogr.am/pison
6680 次点击
所在节点    Python
6 条回复
gcweb
2014-01-21 22:25:06 +08:00
是否一定需要这样的数据结构才能解决问题呢?

我总觉得需要这种hack的代码,本身结构上就需要调整。。。
pohuty
2014-01-22 01:14:58 +08:00
In [2]: from collections import defaultdict

In [3]: a = defaultdict(dict)

In [4]: a['hell']['good']= 1

In [5]: a
Out[5]: defaultdict(<type 'dict'>, {'hell': {'good': 1}})
P9
2014-01-22 09:21:20 +08:00
@gcweb 并非说一定,只是提供一种思路~ 如果能用更好的数据结构,自然不用如此麻烦的做了
P9
2014-01-22 09:22:39 +08:00
@pohuty 这个方式倒也不错,直接用了自带属性。
gully
2014-01-24 22:39:30 +08:00
P9
2014-01-27 13:42:04 +08:00
@gully 哈哈哈,我喜欢这个想法!

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

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

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

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

© 2021 V2EX