簡體   English   中英

如何按鍵值對嵌入的字典列表進行排序?

[英]How to sort embedded list of dictionary by key value?

對於下面嵌入的字典列表,如何根據 key1 路徑的字符串長度對其進行排序?

jobs = [ {"key1":"path/123", "key2":list1}, \
         {"key1":"path/12",  "key2":list2}, \ 
         {"key1":"path/1",   "key2":list3} ]

預期 output

sorted_jobs = [ {"key1":"path/1",   "key2":list3}  \
                {"key1":"path/12",  "key2":list2}, \ 
                {"key1":"path/123", "key2":list1} ]

使用sortedkey參數:

res = sorted(jobs, key=lambda x: len(x["key1"]))
print(res)

Output

[{'key1': 'path/1', 'key2': []}, {'key1': 'path/12', 'key2': []}, {'key1': 'path/123', 'key2': []}]

作為替代方案,您可以使用普通的 Python function,如下所示:

def key(d):
    return len(d["key1"])


res = sorted(jobs, key=key)
print(res)

設置

jobs = [{"key1": "path/123", "key2": []}, \
        {"key1": "path/12", "key2": []}, \
        {"key1": "path/1", "key2": []}]

只需在sorted中定義key function :

sorted_jobs = sorted(jobs, key=lambda d: len(d['key1']))

暫無
暫無

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

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