我有一些字典(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 级嵌套循环。如果我有一个内部循环并且实际上没有嵌套键,那么我会得到值错误。我想在一个单独的列表中获取所有嵌套键,并在另一个列表中的最低级别获取基值或值,我们将不胜感激任何与此相关的帮助。
最佳答案
生成器对这个问题很有用。策略——
键:跟踪当前的递归路径。一碰到树叶就让出当前路径。
值(value)观:只产出叶子。
代码:
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']]
关于python - 从 python 字典中获取所有子键的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55239801/