dissidia
dissidia

Reputation: 1581

Sorting nested dictionaries using its second key

I am trying to sort a nested dictionary using its second key where my dictionary looks like:

my_dictionary = {
    "char": {
        "3": {
            "genman": [
                "motion"
            ]
        }
    }, 
    "fast": {
        "2": {
            "empty": []
        }
    }, 
    "EMPT": {
        "0": {}
    }, 
    "veh": {
        "1": {
            "tankers": [
                "varA", 
                "varB"
            ]
        }
    }
}

And my expected output will be:

my_dictionary = {
    "EMPT": {
        "0": {}
    }, 
    "veh": {
        "1": {
            "tankers": [
                "varA", 
                "varB"
            ]
        }
    },
    "fast": {
        "2": {
            "empty": []
        }
    },
    "char": {
        "3": {
            "genman": [
                "motion"
            ]
        }
    }
}

Tried using the following code:

new_dict = {}
for k, v in my_dictionary.items():
    for s in sorted(my_dictionary.itervalues()):
        if not s.keys()[0]:
            new_val = my_dictionary[k].get(s.keys()[0])
            my_dictionary[s.keys()[0]] = new_val
            my_dictionary.update(new_dict)

It fails badly, and I am getting the same result as my initial dictionary.

Upvotes: 0

Views: 88

Answers (2)

solarc
solarc

Reputation: 5738

This works:

sorted(my_dictionary.items(), key=lambda x: list(x[1].keys())[0])

Returns:

[('EMPT', {'0': {}}),
 ('veh', {'1': {'tankers': ['varA', 'varB']}}),
 ('fast', {'2': {'empty': []}}),
 ('char', {'3': {'genman': ['motion']}})]

Sorted receives a list of key-value pairs, we sort using the result of lambda x: list(x[1].keys())[0] which takes a list of the keys in the inner dict, then grabs the first key (need to do this because dict_keys directly is not indexable).

Edit: the result is a list of key, value pairs but it can be fed into an OrderedDict to use it as a dict.

Upvotes: 2

Woods Chen
Woods Chen

Reputation: 620

actually there is no order for a dict, however you can use OrderedDIct instead.

from collections import OrderedDict
my_dictionary = {
    "char": {
        "3": {
            "genman": [
                "motion"
            ]
        }
    }, 
    "fast": {
        "2": {
            "empty": []
        }
    }, 
    "EMPT": {
        "0": {}
    }, 
    "veh": {
        "1": {
            "tankers": [
                "varA", 
                "varB"
            ]
        }
    }
}
s = sorted((list(v.keys())[0], k) for k, v in my_dictionary.items())
new_dic = OrderedDict([(k,my_dictionary[k]) for _, k in s])

Upvotes: 1

Related Questions