列出嵌套字典的连锁键
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列出嵌套字典的连锁键相关的知识,希望对你有一定的参考价值。
假设我们在下面给出了嵌套字典。最终,我们希望列出每个字典中出现的所有嵌套命名字段。使用句点'。'连接嵌套字段名称。为嵌套记录定义命名字段。按字母顺序显示列表。例如,如果我们的数据文件包含以下内容,那么有序的字段列表将是:
{
"name":{"firstName": "ff", "lastName": "ll"},
"phone": "555",
"address": {
"personal": {"city":"cc", "street": "ss"},
"work": "ww"
}
}
["address.personal.city", "address.personal.street", "email",
"name.firstName", "name.lastName", "phone"]
怎么做?我真的想对每个字典做这样的事情
到目前为止我做了什么:
let X = {"name":{"first":"FFF","last":"LLL"},
"address":{"personal":{"city": "cc", "home":"hh"}, "work":"ww"},
"phone":"555"}
def find_deep(dictionary):
key_list = list(dictionary)
for key in key_list:
if type(dictionary[key])==dict:
key_list[key_list.index(key)] = [key, find_deep(dictionary[key])]
# key_list[key_list.index(key)] = appen_word_to_list(key, list(dictionary[key]))
return key_list
以上功能产生:
y = find_deep(X)
y = ['phone', ['name', ['last', 'first']], ['address',
[['personal', ['city', 'home']], 'work']]]
展开这个,我有错误!
答案
这是使用递归求解的经典问题,递归方法一次添加一个键级别:
def find_deep(dictionary, parent):
ans = []
for key in list(dictionary):
# To make sure the first level doesn't get a preceding dot
initial_dot = "" if parent == "" else "."
if type(dictionary[key]) == dict:
# The recursion progresses
ans.extend(find_deep(dictionary[key], initial_dot.join((parent, key))))
else:
# The recursion terminates
ans.extend([initial_dot.join((parent, key))])
return ans
x = {"name":{"first":"FFF","last":"LLL"},
"address":{"personal":{"city": "cc", "home":"hh"}, "work":"ww"},
"phone":"555"}
print(find_deep(x, ""))
正如预期的那样,输出是:
'name.first', 'name.last', 'address.personal.city', 'address.personal.home', 'address.work', 'phone'
另一答案
你可以使用递归:
s = {
"name":{"firstName": "ff", "lastName": "ll"},
"phone": "555",
"address": {
"personal": {"city":"cc", "street": "ss"},
"work": "ww"
}
}
def trim(f):
return ['.'.join(i.split('.')[:-1]) for i in f(s)]
@trim
def object_notation(s, last = ''):
if not isinstance(s, dict):
yield s
else:
for a, b in s.items():
yield from ['{}.{}'.format(a, i) for i in object_notation(b, a)]
print(object_notation)
输出:
['name.firstName', 'name.lastName', 'phone', 'address.personal.city', 'address.personal.street', 'address.work']
以上是关于列出嵌套字典的连锁键的主要内容,如果未能解决你的问题,请参考以下文章