本文介绍了使用点符号字符串“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.
我的最终问题是:给定 "abcde"
,我需要在字典中创建所有必需的元素,但如果它们已经存在,则不会踩踏它们.
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"检查嵌套字典,自动创建缺失的级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!