如何初始化Python中的嵌套字典 [英] How to initialize nested dictionaries in Python

查看:1507
本文介绍了如何初始化Python中的嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Python v2.7的字典,嵌套在另外一个类似的内容中:

I'm using Python v2.7 dictionaries, nested one inside another like this:

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

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

It seems a bit clumsy to initialize the first level dictionary with an empty dictionary before inserted into the second level dictionary. Is there a way to set a value while at the same time creating a dictionary at the first level if there is not one already there? I imagine something like this to avoid the conditional initializer:

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应该自己初始化为列表?

Also, what if the inner dict should itself initialize to a list?

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)


推荐答案

使用 setdefault


如果键位于字典中,则返回其值。如果没有,请插入一个值为default并返回默认值的键。

If key is in the dictionary, return its value. If not, insert key with a value of default and return default.



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






内部dict:


With lists in the inner dict:

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)






对于深度不详的小数,您可以使用这个小技巧:


For dicts of unknown depth, you can use this little trick:

tree = lambda: defaultdict(tree)

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

这篇关于如何初始化Python中的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆