[英]sort dictionary by multiple keys and values are string,python
I have a dictionary like this: 我有一本这样的字典:
Data={'name':['Sue','Sue','Jim','Lily'],
'Date':['2013-12-11','2013-12-11','2013-11-12','2013-11-12'].
'Time':['12:00:00','11:30:00','10:00:00','13:00:00']}
I want to sort dictionary by name firstly,and then sort by Date,and sort by Time lastly.like this: 我想先按名称对字典排序,然后按日期排序,最后按时间排序。像这样:
Data={'name':['Jim','Lily','Sue','Sue'],
'Date':['2013-11-12','2013-11-12','2013-12-11','2013-12-11'],
'Time':['10:00:00',,'13:00:00','11:30:00','12:00:00']}
I don`t want import any modules. 我不想导入任何模块。
To me it looks like you are assuming each element in each index (of the values in the dictionary) to form a kind of a group , like one group is - 在我看来,您假设每个索引(字典中的值)中的每个元素形成一种组,就像一个组是-
'name':'Sue'
'Date':'2013-12-11'
'Time':'12:00:00'
This seems to be a group, as I can see from your request. 从您的请求中可以看出,这似乎是一个小组。 In such cases, you have your data structure wrong. 在这种情况下,您的数据结构错误。 You should be using a list of dictionaries, where each dictionary is such a group above. 您应该使用词典列表,其中每个词典在上面都是这样的组。
Example of such a list of dictionaries is - 这样的词典列表的示例是-
Data = [{'Date': '2013-12-11', 'Time': '12:00:00', 'name': 'Sue'},
{'Date': '2013-12-11', 'Time': '11:30:00', 'name': 'Sue'},
{'Date': '2013-11-12', 'Time': '10:00:00', 'name': 'Jim'},
{'Date': '2013-11-12', 'Time': '13:00:00', 'name': 'Lily'}]
Once this is done, you can then easily sort this list of dictionaries as - 完成此操作后,您可以轻松地将此字典列表排序为-
sorted(Data, key = lambda x: (x['name'], x['Date'], x['Time']))
Giving the result - 给出结果-
[{'Date': '2013-11-12', 'Time': '10:00:00', 'name': 'Jim'},
{'Date': '2013-11-12', 'Time': '13:00:00', 'name': 'Lily'},
{'Date': '2013-12-11', 'Time': '11:30:00', 'name': 'Sue'},
{'Date': '2013-12-11', 'Time': '12:00:00', 'name': 'Sue'}]
Lots of zip
s, but this sorts the items of the dictionary dependent on each other's values. 大量zip
,但这会根据彼此的值对字典中的项目进行排序。
dict(zip(('name','Date','Time'),zip(*sorted(zip(Data['name'],Data['Date'],Data['Time'])))))
Which gives 这使
{'Date': ('2013-11-12', '2013-11-12', '2013-12-11', '2013-12-11'), 'name': ('Jim', 'Lily', 'Sue', 'Sue'), 'Time': ('10:00:00', '13:00:00', '11:30:00', '12:00:00')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.