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

2024-10-01 17:33:52 发布

您现在位置: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

谢谢大家的帮助


Tags: thenameinforitemsblueredmydict
3条回答

这不是排序,你得到的值比你输入的要多。另外,您不应该使用“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)

首先需要创建一个包含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)]

将字典值合并到元组列表中。使用适当的键函数对列表进行排序。然后可以根据需要格式化打印输出

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

相关问题 更多 >

    热门问题