0

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 Answers3

0

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?

Community
  • 1
  • 1
0

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"]
Chickenmarkus
  • 1,131
  • 11
  • 25
0

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

Kamehameha
  • 5,423
  • 1
  • 23
  • 28
  • Use directly `res=[]` as default value instead of testing for `None`. And replace `type(val)==dict` by the pythonic way Mark Babatunde linked: `isinstance(val, dict)`. – Chickenmarkus Mar 22 '16 at 08:58
  • @Chickenmarkus with `res= []`, we are using mutable types as an optional parameter which could lead to unexpected behaviour later on as the code grows (it's happened to me a couple of times). – Kamehameha Mar 22 '16 at 09:04
  • Aha, this phenomena is called "mutable default arguments". I struggled into it only one time with a more complex type than list. https://pythonconquerstheuniverse.wordpress.com/2012/02/15/mutable-default-arguments/ – Chickenmarkus Mar 23 '16 at 11:57