[英]Python - Sort Dictionary Key Alphabetically while sorting Value list elements by length
我這里有一本字典:
test_dict = {'gfg': ['One', 'six', 'three'],
'is': ['seven', 'eight', 'nine'],
'best': ['ten', 'six']}
我試過了:
for i in range(len(test_dict)):
values = list(test_dict.values())
keys = list(test_dict)
value_sorted_list = values[i]
value_sorted_list = keys[i]
keys_sorted_list = random.shuffle(value_sorted_list)
test_dict.update({f"{keys_sorted_list}":value_sorted_list})
我想按字母順序對鍵進行排序,而值按長度排序是這樣的:
test_dict = {'best': ['six', 'ten'],
'gfg': ['One', 'six', 'three'],
'is': ['nine', 'eight', 'seven]}
我還想要另一個 function 類似於我上面提到的那個,但如果元素的長度相似,則對它們進行隨機排序。
以及另一個 function 隨機排序值列表。
按字母順序對鍵進行排序,按長度對值進行排序。
new_dict = {}
for key in sorted(test_dict.keys()):
sorted_values = sorted(test_dict[key], key=len)
new_dict[key] = sorted_values
print(new_dict)
dict
從 3.7 開始保留插入順序。
在 3.7 版更改:字典順序保證是插入順序。 此行為是 CPython 從 3.6 開始的一個實現細節。
因此,你可以簡單地根據排序后的鍵構造一個新的字典,並保證對應的值是有序的。 從您發布的 output 中,值先按長度排序,然后按字母順序排序。
result = {key: sorted(value, key=lambda x: (len(x), x)) for key, value in sorted(test_dict.items())} # Thanks to Masklinn
print(result)
# {'best': ['six', 'ten'], 'gfg': ['One', 'six', 'three'], 'is': ['nine', 'eight', 'seven']}
參考:
dict-comprehension
- 一種構建字典的方法
sorted
- 這里的key function實現了先按長度再按字母排序。 您可以根據您的排序規則更改它。
這可以通過字典理解來實現,如下所示:
test_dict = {'gfg': ['One', 'six', 'three'],
'is': ['seven', 'eight', 'nine'],
'best': ['ten', 'six']}
new_dict = {k:sorted(v, key=len) for k, v in sorted(test_dict.items())}
print(new_dict)
Output:
{'best': ['ten', 'six'], 'gfg': ['One', 'six', 'three'], 'is': ['nine', 'seven', 'eight']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.