V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
P9
V2EX  ›  Python

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

  •  
  •   P9 · 2014-01-21 17:16:42 +08:00 · 6654 次点击
    这是一个创建于 3754 天前的主题,其中的信息可能已经有所发展或是发生改变。
    希望能做到:
    In [24]: c =dict()
    In [24]: c.people.name = 'roy'

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

    你的方案是?

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

    我总觉得需要这种hack的代码,本身结构上就需要调整。。。
    pohuty
        2
    pohuty  
       2014-01-22 01:14:58 +08:00   ❤️ 1
    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
        3
    P9  
    OP
       2014-01-22 09:21:20 +08:00
    @gcweb 并非说一定,只是提供一种思路~ 如果能用更好的数据结构,自然不用如此麻烦的做了
    P9
        4
    P9  
    OP
       2014-01-22 09:22:39 +08:00
    @pohuty 这个方式倒也不错,直接用了自带属性。
    gully
        5
    gully  
       2014-01-24 22:39:30 +08:00
    P9
        6
    P9  
    OP
       2014-01-27 13:42:04 +08:00
    @gully 哈哈哈,我喜欢这个想法!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2242 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 02:46 · PVG 10:46 · LAX 19:46 · JFK 22:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.