0
votes

I have a JSON object such that:

zt123

zt3653

zt777 ..etc.

I tried the following but think I am over-complicating this. Is there a simplified way?

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
3

3 Answers

0
votes

The chosen answer on this StackOverFlow question may be of service to you: What is the best (idiomatic) way to check the type of a Python variable?

0
votes

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

If it's in a fixed position just call this position:

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

Here's a general way of doing this (For any depth in the 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']

This basically iterates each and every key and uses the startswith function to find out if the key starts with zt