Python 如何根据值字典的长度对嵌套字典进行排序来创建已排序的dict?
我想基于这种类型的字典创建一个排序字典 根据字典里面的长度 所以我的最终输出应该是Python 如何根据值字典的长度对嵌套字典进行排序来创建已排序的dict?,python,python-3.x,Python,Python 3.x,我想基于这种类型的字典创建一个排序字典 根据字典里面的长度 所以我的最终输出应该是 {'M61': {'12': 'options', '14': 'options'}, 'VAMP': {'21': 'Y'} } 像鞋面里面只有1个键值对,M61里面有2个键值对 我试过了 {'VAMP': {'21': 'Y'}, 'M61': {'12': 'options', '14': 'options'} } 但是不幸地失败了,我怎么能实现它呢?你可以使用dict.items()对每个子字典中的
{'M61': {'12': 'options', '14': 'options'},
'VAMP': {'21': 'Y'} }
像鞋面里面只有1个键值对,M61里面有2个键值对
我试过了
{'VAMP': {'21': 'Y'},
'M61': {'12': 'options', '14': 'options'}
}
但是不幸地失败了,我怎么能实现它呢?你可以使用
dict.items()
对每个子字典中的键数进行排序,作为键
sorted_dict = sorted (DictA, key = lambda inner_dict: len (inner_dict ["i"]))
输出将是
DictA = { 'M61': {'12': 'options', '14': 'options'},
'VAMP': {'21': 'Y'},
'VAMP2': {'12': 'options', '14': 'options', '20': 'options', '22': 'options'},
'M62': {'12': 'options', '14': 'options', '20': 'options'}
}
#Sort of dict.items using length of keys of subdictionary as a key
print(dict(sorted(DictA.items(), key=lambda kv:len(kv[1]))))
dict
用于存储键和值,而不是排序。如果您想要一个有序的dict,请执行从集合导入有序dict的操作。是的,对不起,仅在@geetransit进行排序反向如何?您可以在@Ivank中设置reverse=True
{'VAMP': {'21': 'Y'},
'M61': {'12': 'options', '14': 'options'},
'M62': {'12': 'options', '14': 'options', '20': 'options'},
'VAM2': {'12': 'options', '14': 'options', '20': 'options', '22': 'options'}}