Reputation: 43
I am learning a bit of Python at the moment. One of the first tasks I face is to print the keys of a dictionary and its possible nested dictionaries in sorted order.
The task definition is:
Write a program to display all the keys of a 'dictionary of dictionaries' (nested dictionary) in sorted order
So I have something like
vDict={1:2942, 5:{20:231, 49:359, 65:429}, 39:{9359:2932, 9298:29328, 124:4}}
and need to print all of its keys in sorted order. Theoretically, I am not aware of modules so I can only use built in functions
In my mind, the only way I can come up with is to use the output of vDict.keys()
function and split with regex in order to sort the values. But then I have no idea how to iterate through tier 2 dictionaries.
I am pretty sure that is not what I am supposed to do here and there is an easier way. I would be interested to see how an educated mind approaches this.
This is a self study during calm work hours so you are not doing my homework here ;)
Upvotes: 0
Views: 99
Reputation: 2157
This should do it:
def process(dd, keys):
for key, val in dd.items():
keys.append(key)
if isinstance(val,dict):
process(val, keys)
return keys
vDict={1:2942, 5:{20:231, 49:359, 65:429}, 39:{9359:2932, 9298:29328, 124:4}}
keys=[]
process(vDict, keys)
print(sorted(keys))
Upvotes: 3
Reputation: 7377
The oneliner approach
>>> sorted([k for v in vDict.values() if isinstance(v, dict) for k in v] + list(vDict))
[1, 5, 20, 39, 49, 65, 124, 9298, 9359]
The split out, slightly more readable version
>>> def iterate_keys(d):
... for k, v in d.items():
... yield k
... if isinstance(v, dict):
... yield from v
...
>>> sorted(iterate_keys(vDict))
[1, 5, 20, 39, 49, 65, 124, 9298, 9359]
If you wanted to handle dictionaries with deeper nesting, you could change the yield from v
line to yield from iterate_keys(v)
to visit all levels of nesting.
Upvotes: 3
Reputation: 111
I think this is what you are looking for:
vDict={1:2942, 5:{20:231, 49:359, 65:429}, 39:{9359:2932, 9298:29328, 124:4}}
def get_keys(vDict):
keys_list = []
for k in vDict.keys():
keys_list.append(k)
if(type(vDict[k]) is dict):
keys_list = keys_list + get_keys(vDict[k])
return keys_list
new_list = get_keys(vDict)
new_list.sort()
Output:
[1, 5, 20, 39, 49, 65, 124, 9298, 9359]
Upvotes: 2