V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
Ninesir
V2EX  ›  Python

新手问 Python 里的字典只能两两一组么?我想放三四五六七一组怎么办?

  •  
  •   Ninesir · Jul 12, 2020 · 3398 views
    This topic created in 2120 days ago, the information mentioned may be changed or developed.
    刚学两天

    新手问 python 里的字典只能两两一组么?我想放三四五六七一组怎么办?
    dic = {'甲':'A':1,'乙':'B':8,'丙':'C':3}
    9 replies    2020-07-18 17:45:10 +08:00
    Trim21
        1
    Trim21  
       Jul 12, 2020
    dic = {'甲':{'A':1},'乙':{'B':8},'丙':{'C':3}}
    Ninesir
        2
    Ninesir  
    OP
       Jul 12, 2020
    @Trim21 只能两两一组嵌套是吧。
    MooRider
        3
    MooRider  
       Jul 12, 2020
    dict 的 value 不一定为 str, 可以为一个 list, touple 或者是 dict.
    所以只需要{"A":[list1,list2]}
    或者像一楼那样就行
    JieS
        4
    JieS  
       Jul 13, 2020 via iPhone
    键值对,key: value,键和值只能为一个对象…
    "name":["小明","小白"]
    可以用列表来嵌套多个值
    InkStone
        5
    InkStone  
       Jul 13, 2020
    除了一楼的写法之外,还可以用 tuple 做 key 。

    不过 tuple 有个缺点,它是有序的。
    你可以自己实现一个类,内部用 set,然后把它写成 hashable 的,这样就可以支持 unordered tuple……甚至还能支持部分匹配
    edk24
        6
    edk24  
       Jul 13, 2020
    list = [['甲', 'A', 1], ...]

    用列表也祥呀 哈哈
    lithbitren
        7
    lithbitren  
       Jul 13, 2020
    frozenset 就是可 hash 的 set
    volvo007
        8
    volvo007  
       Jul 13, 2020
    只能内部嵌套,除了元组,也可以在内部嵌套 named tuple 这种类型

    set 的话,感觉并不是一个很高效的数据结构,还是避免直接用吧
    SingeeKing
        9
    SingeeKing  
    PRO
       Jul 18, 2020
    我感觉 lz 所谓「一组」的用途可能用 namedtuple 组成的 list 更合适一些
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1181 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 17:15 · PVG 01:15 · LAX 10:15 · JFK 13:15
    ♥ Do have faith in what you're doing.