使用点符号字符串"a.b.c.d.e"检查嵌套字典,会自动创建缺失级别 [英] Checking a nested dictionary using a dot notation string "a.b.c.d.e", automatically create missing levels
本文介绍了使用点符号字符串"a.b.c.d.e"检查嵌套字典,会自动创建缺失级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下字典:
d = {"a":{"b":{"c":"winning!"}}}
我有这个字符串(来自外部来源,我无法更改此隐喻).
I have this string (from an external source, and I can't change this metaphor).
k = "a.b.c"
我需要确定字典是否具有键 'c'
,所以如果没有,我可以添加它.
I need to determine if the dictionary has the key 'c'
, so I can add it if it doesn't.
这可轻松检索点表示法值:
This works swimmingly for retrieving a dot notation value:
reduce(dict.get, key.split("."), d)
但是我不知道如何减少" has_key
支票或类似的东西.
but I can't figure out how to 'reduce' a has_key
check or anything like that.
我的最终问题是:给定"a.b.c.d.e"
,我需要在字典中创建所有必需的元素,但是如果它们已经存在,则不要踩踏它们.
My ultimate problem is this: given "a.b.c.d.e"
, I need to create all the elements necessary in the dictionary, but not stomp them if they already exist.
推荐答案
...或使用递归:
def put(d, keys, item):
if "." in keys:
key, rest = keys.split(".", 1)
if key not in d:
d[key] = {}
put(d[key], rest, item)
else:
d[keys] = item
def get(d, keys):
if "." in keys:
key, rest = keys.split(".", 1)
return get(d[key], rest)
else:
return d[keys]
这篇关于使用点符号字符串"a.b.c.d.e"检查嵌套字典,会自动创建缺失级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文