使用第二个键对嵌套词典进行排序

时间:2019-03-19 22:44:40

标签: python dictionary dictionary-comprehension

我正在尝试使用第二个键对嵌套字典进行排序,其中第二个键的字典如下:

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

我的预期输出将是:

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

尝试使用以下代码:

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)

它严重失败,并且我得到的结果与最初的字典相同。

2 个答案:

答案 0 :(得分:2)

这有效:

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

返回:

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

Sorted接收键-值对的列表,我们使用lambda x: list(x[1].keys())[0]的结果进行排序,该结果获取内部dict中的键的列表,然后获取第一个键(需要这样做是因为dict_keys直接是不可索引)。

编辑:结果是键,值对的列表,但可以将其输入到OrderedDict中以用作字典。

答案 1 :(得分:1)

实际上没有命令,但是您可以使用OrderedDIct。

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])
相关问题