简体   繁体   English

在python中对字典的键进行排序

[英]Sort the keys of a dictionary in python

dict: 字典:

d1 = {'b,a':12,'b,c,a':13}

Code: 码:

x = collections.OrderedDict(sorted(d1.items()))
print(x)

Not getting the expected output. 没有得到预期的输出。

Expected Output: 预期产量:

d1 = {'a,b': 12, 'a,b,c':13}

It looks like you don't actually want to sort the keys, you want to re-arrange the non-comma substrings of your keys such that these substrings are ordered. 看起来您实际上并不想对键进行排序,而是想要重新排列键的非逗号子字符串,以便这些子字符串排序。

>>> d1 = {'b,a':12,'b,c,a':13}
>>> {','.join(sorted(key.split(','))):val for key, val in d1.items()}
{'a,b': 12, 'a,b,c': 13}

d1.items(): returns a list of (key, value) tuples d1.items():返回(键,值)元组的列表

sorted(d1.items()): simply sorts the above list sorted(d1.items()):仅对上面的列表进行排序

If you want to sort the items in your keys, then you need to run sort on your keys. 如果要对键中的项目进行排序,则需要对键进行排序。

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

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