简体   繁体   English

如果密钥存在,则按键对字典进行排序,如果密钥不存在于列表的末尾

[英]Sort a dictionary by key if the key exists, if it doesn't put it to the end of the list

Been scratching my head on how to accomplish this, 一直在试着如何做到这一点,

sorted_dict = sorted(dict['values'],
                    key=lambda k: k['a']['b'])

Now in this dict some values of a have ab value, while some don't. 现在在这个词典中,一些a值具有ab值,而有些则没有。 I want it to sort by b values and if it doesn't exist, just put it at the back of the list. 我希望它按b值排序,如果它不存在,只需将它放在列表的后面。 Is there anyway to do without some complex code such as splitting the values of a for those that have ab value and those that don't? 反正有没有一些复杂的代码,例如为具有ab值的那些和不具有ab值的那些分割a的值?

不。

key=lambda k: ('b' not in k['a'], k['a'].get('b', None))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM