我有一些字典(json输出)。我想获取基本元素,它可以是字符串列表或字符串。目前,我正在这样做:-
folder="shared/"
files=os.listdir('shared')
for f in files:
f=folder+f
print(f)
with open(f) as f:
data = json.load(f)
#data is a dict now with sub-keys
for key,value in data.items():
if value.keys():
print(value)
break
这是python代码读取的输入字典:-
{
"shortshirt": {
"ralphlauren": {
"classic": [
"That Ralph Lauren classic fit is a timeless look!",
"Nice choice. Can’t go wrong with Ralph Lauren"
]
}
},
"socks": {
"": {
"": ["Have to find the right socks to keep your feet cozy"]
}
}
}
这是我得到的输出:-
{'ralphlauren': {'classic': ['That Ralph Lauren classic fit is a timeless look!', 'Nice choice. Can’t go wrong with Ralph Lauren']}}
{'': {'': ['Have to find the right socks to keep your feet cozy']}}
但这就是我想要的:-
keys=[["shortshirt","ralphlauren","classic"],["socks"]]
value=[['That Ralph Lauren classic fit is a timeless look!', 'Nice choice. Can’t go wrong with Ralph Lauren'], ['Have to find the right socks to keep your feet cozy']]
但是我不知道是2层还是3层嵌套循环。如果我有一个内部循环,并且实际上没有嵌套键,那么我会得到值错误。我想在一个单独的列表中获取所有嵌套键,并在另一个列表中获取一个或多个基值,例如最低级别,对此的任何帮助将不胜感激。
答案 0 :(得分:1)
生成器对于解决此问题很有用。策略–
键:跟踪当前递归路径。碰到叶子就产生当前路径。
值:仅产生叶子。
代码:
def getitems(obj):
def getkeys(obj, stack):
for k, v in obj.items():
k2 = ([k] if k else []) + stack # don't return empty keys
if v and isinstance(v, dict):
for c in getkeys(v, k2):
yield c
else: # leaf
yield k2
def getvalues(obj):
for v in obj.values():
if not v: continue
if isinstance(v, dict):
for c in getvalues(v):
yield c
else: # leaf
yield v if isinstance(v, list) else [v]
return list(getkeys(obj,[])), list(getvalues(obj))
输入:
{
"shortshirt": {
"ralphlauren": {
"classic": [
"That Ralph Lauren classic fit is a timeless look!",
"Nice choice. Can't go wrong with Ralph Lauren"
]
}
},
"socks": {
"": {
"": ["Have to find the right socks to keep your feet cozy"]
}
}
}
输出:
# keys
[['classic', 'ralphlauren', 'shortshirt'], ['socks']]
# values
[['That Ralph Lauren classic fit is a timeless look!', "Nice choice. Can't go wrong with Ralph Lauren"], ['Have to find the right socks to keep your feet cozy']]