我有这样的字典:
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']}
我想首先按名称对字典进行排序,然后按日期排序,最后按时间排序。就像这样:
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']}
我不想导入任何模块。
答案 0 :(得分:2)
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'}]
答案 1 :(得分:1)
很多zip
,但这会根据彼此的值对字典中的项目进行排序。
dict(zip(('name','Date','Time'),zip(*sorted(zip(Data['name'],Data['Date'],Data['Time'])))))
哪个给出了
{'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')}