Home > Net >  How to sort embedded list of dictionary by key value?
How to sort embedded list of dictionary by key value?

Time:11-26

For below embedded list of dictionary, how to sort it according to key1 path's string length?

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

Expected output

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

CodePudding user response:

Use the key parameter of sorted:

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

Output

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

As an alternative you could use a normal Python function, as below:

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


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

Setup

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

CodePudding user response:

Just define the key function in sorted:

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