Reputation: 139
I have a list of dicts in python which look like these:
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
I want to sort them by day of week such that the result is
[{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']}]
I can use this answer to sort list of just weekday names: Sort week day texts but is there a way to sort the above dict?
Upvotes: 0
Views: 916
Reputation: 781771
Use a lambda function that extracts the weekday name from the dictionary and then returns the index as in your linked question.
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"]
list_of_dicts =
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
list_of_dicts.sort(key = lambda d: weekdays.index(d['day']))
Upvotes: 2
Reputation: 5479
Here it is:
lst = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Friday' , 'workers' : ['Nelly']}]
m = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
result = sorted(lst, key= lambda x: m.index(x['day']))
print(result)
#[{'day': 'Monday', 'workers': ['Kelly']}, {'day': 'Wednesday', 'workers': ['John', 'Smith']}, {'day': 'Friday', 'workers': ['Nelly']}]
Upvotes: 0
Reputation: 1570
To sort a dictionary by a key "key"
, you can do:
sorted(dicts, key=lambda d: d["key"])
Merging this with the answer from the question you linked:
m = ["Monday", "Tuesday", ...]
print(sorted(dicts, key=lambda d: m.index(d["day"])))
Upvotes: 1
Reputation: 2747
The same basic approach that the example you link to uses will work for your list of dictionaries case. The trick is, you need to extract the day value from the dictionaries within the list to make it work. A lambda
expression used for the key
parameter is one way to do that.
Example:
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
data = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}]
sorted(data, key=lambda d: day_order.index(d["day"]))
Output:
[{'day': 'Monday', 'workers': ['Kelly']},
{'day': 'Wednesday', 'workers': ['John', 'Smith']}]
Upvotes: 4