gpt4 book ai didi

python - 通过定义排序顺序,根据子字典键对 python 字典键进行排序

转载 作者:太空狗 更新时间:2023-10-29 23:56:57 27 4
gpt4 key购买 nike

我的问题是对 another question 的扩展其中 OP 有一本字典,即下面的字典,并希望根据子字典键对主键进行排序

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'}
}

提议的(在下面引用的)解决方案非常有效。

dicts = myDict.items()
dicts.sort(key=lambda (k,d): (d['site_location'], d['serial_num'],))

但是,此解决方案对所有内容都按升序排序(按降序排序很简单)。我想知道是否可以定义排序顺序的混合,比如 serial_num 升序但 site_location 降序?

最佳答案

这是一个可能的解决方案,因为列表排序是 stable .我稍微更改了数据以证明它有效。

此方法在Python documentation中也有规定。 .

myDict = {
'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'},
'ABC12346': {'serial_num': 'ABC12345', 'site_location': 'Europe'},
'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'},
'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'},
'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'}
}

result = sorted(myDict.items(), key=lambda x: x[1]['site_location'], reverse=True)
result = sorted(result, key=lambda x: x[1]['serial_num'])

# [('ABC12345', {'serial_num': 'ABC12345', 'site_location': 'South America'}),
# ('ABC12346', {'serial_num': 'ABC12345', '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'})]

关于python - 通过定义排序顺序,根据子字典键对 python 字典键进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49121246/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com