有没有一种方法可以使字典的字典顺序忽略大小写?现在,我知道按字典的字典顺序排列,但仍然困惑如何忽略小写和大写。这是我尝试过的一些代码。
dic={'subject':'math','name':'','PS':'$'}
for key,value in sorted(dic.items()):
print(key+'='+value)
现在,我得到的结果是 PS = $ 在第一位,但我想在中间,如下所示:
name=
PS=$
subject=math
答案 0 :(得分:1)
就地:不可能
原因::修改键后,将无法使用修改后的键从同一本旧字典中检索原始值。唯一的解决方法是将修改后的密钥与原始密钥一起存储。
创建一个临时词典,例如dic_lex
。
将修改后的密钥(小写)存储为key
,原始密钥存储为value
:
dic={'subject':'math','name':'','PS':'$'}
dic_lex={key.lower() : key for key in dic.keys()}
for key in sorted(dic_lex.keys()):
print(dic_lex[key]+'='+dic[dic_lex[key]])
打印:
name=
PS=$
subject=math
答案 1 :(得分:1)
在Python 3.6和3.7中,字典按插入顺序排列,但是最好使用OderedDict
Are dictionaries ordered in Python 3.6+?
from collections import OrderedDict
dic={'subject':'math','name':'','PS':'$'}
dic_ord = OrderedDict(sorted(dic.items(), key=lambda t: t[0].lower()))
for key,value in dic_ord.items():
print(key, '=', value)
答案 2 :(得分:1)
将sorted
与字典构造函数一起使用
dic = dict(sorted(dic.items(), key=lambda x: x[0].lower()))
# {'name': '', 'PS': '$', 'subject': 'math'}