• 请不要在回答技术问题时复制粘贴 AI 生成的内容
ithelloworld
V2EX  ›  程序员

python dict vs ruby hash

  •  
  •   ithelloworld · Mar 22, 2013 · 3601 views
    This topic created in 4842 days ago, the information mentioned may be changed or developed.
    ruby中hash

    grades = Hash.new
    grades["a"] << 1
    grades["b"] << 2
    grades["c"] << 3
    ...

    这样的用法,python用dict怎么实现?

    注意不是给一个key简单地赋值,而是要用 grades["a"] 装很多值。
    4 replies    1970-01-01 08:00:00 +08:00
    binux
        1
    binux  
       Mar 22, 2013
    grades.setdefault("a", []).append(1)
    ithelloworld
        2
    ithelloworld  
    OP
       Mar 22, 2013
    @binux 以此类推,其它的值这样添加?

    grades.setdefault("b", []).append(2)
    grades.setdefault("c", []).append(3)
    orzfly
        3
    orzfly  
       Mar 22, 2013
    我怎么都觉得是Hash.new{[]}吧
    ithelloworld
        4
    ithelloworld  
    OP
       Mar 22, 2013
    @orzfly 你是说ruby的写法吗?应该是这样:

    Hash.new{|h, key| h[key] = []}
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3803 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 05:07 · PVG 13:07 · LAX 22:07 · JFK 01:07
    ♥ Do have faith in what you're doing.