【问题标题】:How to initialize nested dictionaries in Python如何在 Python 中初始化嵌套字典
【发布时间】:2013-03-27 00:18:11
【问题描述】:

我正在使用 Python v2.7 字典,像这样嵌套在另一个字典中:

def example(format_str, year, value):
  format_to_year_to_value_dict = {}
  # In the actual code there are many format_str and year values,
  # not just the one inserted here.
  if not format_str in format_to_year_to_value_dict:
    format_to_year_to_value_dict[format_str] = {}
  format_to_year_to_value_dict[format_str][year] = value

在插入二级字典之前用空字典初始化一级字典似乎有点笨拙。如果还没有一个字典,有没有办法在第一级创建字典的同时设置一个值?我想像这样避免条件初始化器:

def example(format_str, year, value):
  format_to_year_to_value_dict = {}
  add_dict_value(format_to_year_to_value_dict[format_str], year, value)

另外,如果内部 dict 本身应该初始化为一个列表呢?

def example(format_str, year, value):
  format_to_year_to_value_dict = {}
  # In the actual code there are many format_str and year values,
  # not just the one inserted here.
  if not format_str in format_to_year_to_value_dict:
    format_to_year_to_value_dict[format_str] = {}
  if not year in format_to_year_to_value_dict[format_str]:
    format_to_year_to_value_dict[format_str][year] = []
  format_to_year_to_value_dict[format_str][year].append(value)

【问题讨论】:

    标签: python dictionary python-2.7 initialization nested


    【解决方案1】:

    使用setdefault:

    如果键在字典中,则返回其值。如果不是,则插入值为默认值的键并返回默认值。

    format_to_year_to_value_dict.setdefault(format_str, {})[year] = value
    

     

    collections.defaultdict:

    format_to_year_to_value_dict = defaultdict(dict)
    ...
    format_to_year_to_value_dict[format_str][year] = value
    

    在内部字典中有列表:

    def example(format_str, year, value):
      format_to_year_to_value_dict = {}
    
      format_to_year_to_value_dict.setdefault(format_str, {}).setdefault(year, []).append(value)
    

    def example(format_str, year, value):
      format_to_year_to_value_dict = defaultdict(lambda: defaultdict(list))
    
      format_to_year_to_value_dict[format_str][year].append(value)
    

    对于未知深度的字典,你可以使用这个小技巧:

    tree = lambda: defaultdict(tree)
    
    my_tree = tree()
    my_tree['a']['b']['c']['d']['e'] = 'whatever'
    

    【讨论】:

    • 在内部 dict 案例中的列表是否有类似 defaultdict 的东西?
    • 只是在编辑它。您只需要一个返回 defaultdict(list) 的函数,而不仅仅是 {} 丢失键。
    【解决方案2】:
    from collections import defaultdict
    format_to_year_to_value_dict = defaultdict(dict)
    

    这将创建一个字典,当您访问不存在的键时调用 dict()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2020-04-09
      相关资源
      最近更新 更多