Python:动态获取字典中的子字典? [英] python: getting sub-dicts in dicts dynamically?

查看:77
本文介绍了Python:动态获取字典中的子字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想编写一个函数,该函数将从dict返回任意值,例如: mydict ['foo'] ['bar'] ['baz'] ,或返回空如果不是,则为字符串.但是,我不知道 mydict ['foo'] 是否一定存在,更不用说 mydict ['foo'] ['bar'] ['baz'] .

Say I want to write a function which will return an arbitrary value from a dict, like: mydict['foo']['bar']['baz'], or return an empty string if it doesn't. However, I don't know if mydict['foo'] will necessarily exist, let alone mydict['foo']['bar']['baz'].

我想做类似的事情:

safe_nested(dict, element):
  try:
    return dict[element]
  except KeyError:
    return ''

但是我不知道如何编写将接受函数中查找路径的代码.我开始沿接受句点分隔的字符串(例如 foo.bar.baz )的路线,以便此函数可以递归地尝试获取下一个子字典,但这并不像Python一样.我想知道是否有一种方法可以同时传递dict( mydict )和我感兴趣的子结构( ['foo'] ['bar'] ['baz'] ),并让该函数尝试访问它或在遇到 KeyError 时返回空字符串.

But I don't know how to approach writing code that will accept the lookup path in the function. I started going down the route of accepting a period-separated string (like foo.bar.baz) so this function could recursively try to get the next sub-dict, but this didn't feel very Pythonic. I'm wondering if there's a way to pass in both the dict (mydict) and the sub-structure I'm interested in (['foo']['bar']['baz']), and have the function try to access this or return an empty string if it encounters a KeyError.

我要以正确的方式解决这个问题吗?

Am I going about this in the right way?

推荐答案

您应该使用标准的 defaultdict :有关如何嵌套它们的信息,请参见: defaultdict嵌套的defaultdict Python中"collection.defaultdict"的多个级别

For how to nest them, see: defaultdict of defaultdict, nested or Multiple levels of 'collection.defaultdict' in Python

我认为这可以满足您的要求

I think this does what you want:

from collections import defaultdict
mydict = defaultdict(lambda: defaultdict(lambda: defaultdict(str)))

这篇关于Python:动态获取字典中的子字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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