【问题标题】:Python: Concise way of updating a dictionaryPython:更新字典的简洁方法
【发布时间】:2017-12-19 03:47:30
【问题描述】:

当我使用值是列表的字典时,我经常会编写这样的代码:

if k in D:
    D[k].append(x)
else:
    D[k] = [x]

有更简洁的方法吗?

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    您可以使用collections.defaultdict

    from collections import defaultdict
    D = defaultdict(list)
    D[k].append(x)
    

    【讨论】:

      【解决方案2】:

      最简洁的方式是使用setdefaultlike:

      D.setdefault(k, []).append(x)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-23
        • 1970-01-01
        • 2017-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多