gpt4 book ai didi

python - 如何做不区分大小写的字典并将它们存储在 OrderedDict 中

转载 作者:行者123 更新时间:2023-11-28 16:32:16 24 4
gpt4 key购买 nike

我有以下集合字典:

named_sets  = {'DMXAA':set(['1441326_at', '1460062_at']), 'cdiGMP':set(['1441326_at', '1460062_at']),'cGAMP': set(['1441326_at', '1460062_at'])  }

我想做的是使用不区分大小写的方式进行键排序并将它们存储在 OrderedDict 中,产生:

OrderedDict([ 
('cdiGMP', set(['1441326_at', '1460062_at'])),
('cGAMP', set(['1441326_at', '1460062_at'])),
('DMXAA', set(['1441326_at', '1460062_at'])),
])

我试过了但是失败了:

from collections import OrderedDict
named_sets = {'DMXAA':set(['1441326_at', '1460062_at']), 'cdiGMP':set(['1441326_at', '1460062_at']),'cGAMP': set(['1441326_at', '1460062_at']) }
OrderedDict(sorted(named_sets.items()))

给出:

OrderedDict([('DMXAA', set(['1441326_at', '1460062_at'])), ('cGAMP', set(['1441326_at', '1460062_at'])), ('cdiGMP', set(['1441326_at', '1460062_at']))])

最佳答案

您需要提供一个 key 函数来不区分大小写地进行排序。

在 Python 3 上你会使用 str.casefold() function , 在 Python 2 上坚持 str.lower() 是好的:

OrderedDict(sorted(named_sets.items(), key=lambda i: i[0].lower()))

注意 lambda;您正在对 key-value 对进行排序,但是 set 对象是不可排序的,因此您只想返回键,折叠以进行不区分大小写的比较。

演示:

>>> from collections import OrderedDict
>>> named_sets = {'DMXAA':set(['1441326_at', '1460062_at']), 'cdiGMP':set(['1441326_at', '1460062_at']),'cGAMP': set(['1441326_at', '1460062_at']) }
>>> OrderedDict(sorted(named_sets.items(), key=lambda i: i[0].lower()))
OrderedDict([('cdiGMP', set(['1441326_at', '1460062_at'])), ('cGAMP', set(['1441326_at', '1460062_at'])), ('DMXAA', set(['1441326_at', '1460062_at']))])
>>> _.keys()
['cdiGMP', 'cGAMP', 'DMXAA']

关于python - 如何做不区分大小写的字典并将它们存储在 OrderedDict 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30680866/

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