Skip to content Skip to sidebar Skip to footer

Get Final Elements Of Nested Dictionary In Python

How do I get the latest elements of the nested dictionary by one or few keys? For example my nested dict is: { 'key_1' : { 'key_1_1' : {

Solution 1:

A simple recursive function should do what you're looking for:

defvals(x):
    ifisinstance(x, dict):
        result = []
        for v in x.values():
            result.extend(vals(v))
        return result
    else:
        return [x]

used as..

>>>d = {1:2, 3:{4:5, 6:7}}>>>vals(d)
[2, 5, 7]
>>>vals(d[1])
[2]
>>>vals(d[3])                                                                  
[5, 7]

Post a Comment for "Get Final Elements Of Nested Dictionary In Python"