我有一本看起来像这样的字典:
myDict = {
'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'},
'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'},
'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'},
'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'},
'ABC12346': {'serial_num': 'ABC12346', 'site_location': 'Europe'}
}
我的目标是按每个子词典的 thesite_location
和 the对这本词典进行排序。serial_num
使用我在这个问题中找到的代码 -对字典字典进行排序 python - 我能够对其进行排序,但这并不是我所期望的。
这是我的代码:
import pprint
items = ((k, k2, v) for k in myDict for k2, v in myDict[k].items())
ordered = sorted(items, key=lambda x:x[-1], reverse=False)
pprint.pprint(ordered)
这是我得到的结果:
[('ABC12346', 'site_location', 'Europe'),
('SER12345', 'site_location', 'North America'),
('SER12346', 'site_location', 'North America'),
('SER12347', 'site_location', 'South America'),
('ABC12345', 'site_location', 'South America'),
('ABC12346', 'serial_num': 'ABC12346'),
('SER12345', 'serial_num': 'SER12345'),
('SER12346', 'serial_num': 'SER12346'),
('SER12347', 'serial_num': 'SER12347'),
('ABC12345', 'serial_num': 'ABC12345')]
我期待着更像这样的东西:
{
'ABC12346': {'serial_num': 'ABC12346', 'site_location': 'Europe'}
'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'},
'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'},
'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'},
'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'},
}
实际结果是将序列号和站点位置分开。我想把它们放在排序的对象中。我怎样才能做到这一点?