按字典的嵌套字典值对字典进行排序

时间:2021-03-08 21:39:38

标签: python

这是我的输入数据:

Mydict = {
'Red': {'Pesho': 1250000, 'Chicho': 101},
'Blue': {'Pesho': 10000, 'Gosho': 10000, 'Jecho': 260000},
'White': {'Bobo': 10, 'Bebo': 10, 'Bibo': 100, 'Bubo': 10}
}

我想先按嵌套字典的值然后按它们的长度对输出进行排序。如何做到这一点?

输出应如下所示:

(Red) Pesho <-> 1250000
(Blue) Jecho <-> 260000
(Blue) Pesho <-> 10000
(Blue) Gosho <-> 10000
(Red) Chicho <-> 101
(White) Bibo <-> 100
(White) Bobo <-> 10
(White) Bebo <-> 10
(White) Bubo <-> 10

在挖掘更多之后,我想出了这个:

sorted_Mydict = dict(sorted(Mydict.items(), key=lambda x: -len(x[1].values()))) #Making a new order by the count of the nested dictionarie values
pairs = [(color, name, power) for color, inner in sorted_Mydict.items() for name, power in inner.items()] #Then creating list of pairs, as suggested in the comments
[print(f"({color}) {name} <-> {power}") for color, name, power in sorted(pairs, key=lambda x: -x[2])] #Finally printing in the desired format, ordered by the int values

感谢大家的帮助!

3 个答案:

答案 0 :(得分:1)

这不是排序,你得到的值比你输入的要多。另外,你不应该使用“dict”作为你的 dict 的名字,因为它是一个 python 方法。 不过,这是一个有效的答案:)

myDict = {
'Red': {'Pesho': 1250000, 'Chicho': 101},
'Blue': {'Pesho': 10000, 'Gosho': 10000, 'Jecho': 260000},
'White': {'Bobo': 10, 'Bebo': 10, 'Bibo': 100, 'Bubo': 10}
}


def getValue(x):
    return -x["Value"] #minus to invert sort

myDictList=[]
for key1 in myDict.keys():
    for key2 in myDict[key1].keys():
        myDictList.append({"Color":key1,"Name":key2,"Value":myDict[key1][key2]})


myDictList.sort(key=getValue)
print(myDictList)

答案 1 :(得分:1)

您首先需要创建一个包含 3 个元素的元组列表 color, name, value 的结构,然后根据您的条件对其进行排序

values = {
    'Red': {'Pesho': 1250000, 'Chicho': 101},
    'Blue': {'Pesho': 10000, 'Gosho': 10000, 'Jecho': 260000},
    'White': {'Bobo': 10, 'Bebo': 10, 'Bibo': 100, 'Bubo': 10}
}

pairs = [(outer_key, inner_key, value) for outer_key, inner in values.items() 
                                       for inner_key, value in inner.items()]

pairs.sort(key=lambda x: (-x[2], len(x[1])))
print(pairs[:3])  # [('Red', 'Pesho', 1250000), ('Blue', 'Jecho', 260000), ('Blue', 'Pesho', 10000)]

答案 2 :(得分:1)

将字典值组合成一个元组列表。使用适当的键功能对列表进行排序。然后,您可以根据需要格式化打印输出。

myDict = {
'Red': {'Pesho': 1250000, 'Chicho': 101},
'Blue': {'Pesho': 10000, 'Gosho': 10000, 'Jecho': 260000},
'White': {'Bobo': 10, 'Bebo': 10, 'Bibo': 100, 'Bubo': 10}
}

r = [(C,K,n) for C,d in myDict.items() for K,n in d.items()]
r.sort(key=lambda ckn:ckn[-1], reverse=True)

for C,K,n in r: print(f"({C}) {K},<-> {n}")

(Red) Pesho,<-> 1250000
(Blue) Jecho,<-> 260000
(Blue) Pesho,<-> 10000
(Blue) Gosho,<-> 10000
(Red) Chicho,<-> 101
(White) Bibo,<-> 100
(White) Bobo,<-> 10
(White) Bebo,<-> 10
(White) Bubo,<-> 10