簡體   English   中英

我有一本字典 {string and int}。 如何比較整數值而不是同一字典中的鍵(python)

[英]I have a dictionary {string and int}. How do I compare integers values and not the keys within the same dictionary(python)

我有一本人的字典,如果年齡相同,我想按姓名字母順序對人進行排序,如果年齡不同,我想按年齡降序排列。 所以基本上,我需要返回兩個輸出。 到目前為止,這是我所擁有的,但它沒有考慮到條件。 我如何比較每個項目的年齡值並將其添加到不同的列表中然后對其進行排序?

people = {'Steve' : 20 , 'David': 21 , 'Andrew' : 19 , 'Bruce': 22 ,'James' : 20 , 'Dave': 26 ,'Smith' : 19}
print('Sorted People in Alphabetical Order: ', dict(sorted(people.items())))
print('Sorted People in Numerical Order: ',dict(sorted(people.items(), key=lambda item: item[1])))

我想要的 output 是按字母順序排列的同齡人:{(Andrew,19), (James,20), (Smith, 19), (Steve, 20)}

按年齡對不同年齡排序:{(David,21), (Bruce,22), (Dave,26)}

您可以將tuple傳遞給sortedkey 首先根據年齡排序,然后對基本字母表進行排序。

people = {'Steve' : 20 , 'David': 21 , 'Andrew' : 19 , 'Bruce': 22 ,'James' : 20 , 'Dave': 26 ,'Smith' : 19}

res = dict(sorted(people.items(), key=lambda x: (x[1], x[0])))
# -------------------------------------------x[1]^^^ is value -> age
# ---------------------------------------------------x[0]^^^ is key -> alphabet
print(res)

Output:

{'Andrew': 19,
 'Smith': 19,
 'James': 20,
 'Steve': 20,
 'David': 21,
 'Bruce': 22,
 'Dave': 26}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM