嵌套字典,返回Python中特定的键

2024-09-28 16:57:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON对象:

zt123型

zt3653型

zt777…等

我已经试过了,但我想这会让事情变得复杂。有没有简化的方法?在

def extract(dict_in, dict_out):
    for key, value in dict_in.iteritems():
        if isinstance(value, dict): # If value itself is dictionary
            extract(value, dict_out)
        elif isinstance(value, unicode):
            # Write to dict_out
            dict_out[key] = value
    return dict_out

Tags: 对象方法keyinjsonvaluedefextract
3条回答

在这个StackOverFlow问题上选择的答案可能会对您有所帮助: What is the best (idiomatic) way to check the type of a Python variable?

这里有一个一般的方法来做这个(对于任何深度的dict)—

# This function takes the dict and required prefix
def extract(d, prefix, res=None):
    if not res:
        res = []
    for key, val in d.iteritems():
        if key.startswith(prefix):
            res.append(key)
        if type(val) == dict:
            res = extract(val, prefix, res[:])
    return res

# Assume this to be a sample dictionary - 
d = {"zt1": "1", "zt2":{"zt3":{"zt4":"2"}}}
res = extract(d, "zt")
print res

# Outputs- 
['zt1', 'zt2', 'zt3', 'zt4']

这基本上迭代每个键,并使用startswith函数来确定该键是否以zt开头

these will always be nested in >interfaces >interface >zt

如果它在一个固定的位置,就叫这个位置:

hosts1_xxxxxxx= {
    "line": {}, 
    "interfaces": {
        "interface": {
            "zt123": {},
            "zt456": {},
        },
    },
}
zts = list(hosts1_xxxxxxx["interfaces"]["interace"].keys())
print(zts)
# ["zt123", "zt456"]

相关问题 更多 >