【问题标题】:Dynamically create nested dictionaries动态创建嵌套字典
【发布时间】:2021-10-03 23:38:27
【问题描述】:

我想创建一个字典词典。这些值将动态创建,我很好奇是否有更好、更 Python 的方式来执行以下操作:

#!python3

dict = {}
persons = ('jack', 'jill', 'fido', 'spot')
for person in persons:
  if person not in dict:
    dict[person] = {}
    dict[person]['count'] = 1
  else:
    dict[person]['count'] += 1

这显然是伪代码,仅供学习使用 :) 感谢您的帮助!

【问题讨论】:

    标签: python-3.x dictionary


    【解决方案1】:

    当您发现自己编写了大量样板代码来设置默认值时,是查看collections.defaultdict 的好时机。

    这将让您为任何新键建立默认值。

    from collections import defaultdict
    
    d = defaultdict(lambda: {'count': 0})
    
    persons = ('jack', 'jill', 'fido', 'spot', 'jack')
    
    for person in persons:
        d[person]['count'] += 1
    

    另外,由于您正在计算列表中值的数量,因此值得查看collections.Counter。这将自动为您计算。所以

    from collections import Counter
    
    Counter(persons)
    # Counter({'jack': 2, 'jill': 1, 'fido': 1, 'spot': 1})
    

    如果你需要子字典,你可以把它放在字典理解中:

    d = {k: {'count':v} for k, v in Counter(persons).items()}
    

    导致

    {'jack': {'count': 2},
     'jill': {'count': 1},
     'fido': {'count': 1},
     'spot': {'count': 1}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 2021-04-04
      • 2017-02-08
      • 1970-01-01
      相关资源
      最近更新 更多