gpt4 book ai didi

python - 如何通过根据值字典的长度对嵌套字典进行排序来创建排序字典?

转载 作者:太空宇宙 更新时间:2023-11-04 11:17:25 24 4
gpt4 key购买 nike

{'M61': {'12': 'options', '14': 'options'},
'VAMP': {'21': 'Y'} }

我想基于这种类型的字典创建一个排序的字典。

根据里面字典的长度。

所以我的最终输出应该是这样的

{'VAMP': {'21': 'Y'},
'M61': {'12': 'options', '14': 'options'}
}

像 VAMP 内部只有 1 个键值对,而 M61 有 2 个

我试过了

sorted_dict = sorted (DictA, key = lambda inner_dict: len (inner_dict ["i"]))

但是我不知道如何实现它,惨遭失败?

最佳答案

您可以使用dict.items() 对每个子词典中的键数作为

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]))))

输出将是

{'VAMP': {'21': 'Y'}, 
'M61': {'12': 'options', '14': 'options'},
'M62': {'12': 'options', '14': 'options', '20': 'options'},
'VAM2': {'12': 'options', '14': 'options', '20': 'options', '22': 'options'}}

关于python - 如何通过根据值字典的长度对嵌套字典进行排序来创建排序字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720991/

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