简体   繁体   English

你如何按字母顺序排列字典?

[英]How do you alphabetize a dictionary?

I have a dictionary pickled in python as:我有一本在 python 中腌制的字典:

my_dictionary = {'abc': '123', 'def': '456', 'ABC': '123', 'Abc': '123', 'DEF': '456', 'Def': '456'}

What to call a function that sorts the dictionary out as:调用 function 将字典排序为:

my_dictionary = {'abc':'123', 'Abc':'123', 'ABC':'123', 'def':'456', 'Def':'456', 'DEF':'456'}

Currently I unpickle the dictionary and copy the dictionary to a list of tuples.目前我解开字典并将字典复制到元组列表中。 Then sort the tuples and dump the dictionary back in.然后对元组进行排序并将字典转储回去。

Specifically, is there a way to sort the dictionary by its keys as (abc, Abc, ABC)?具体来说,有没有办法通过它的键对字典进行排序(abc,Abc,ABC)? Or sort it as a list tuples (abc, Abc, ABC)?或者将其排序为列表元组(abc、Abc、ABC)?

Thanks谢谢

As long as you are using Python3.7+ (technically 3.6+), where dictionaries are in insertion order, you can make a new dictionary which will be in sorted order.只要您使用的是 Python3.7+(技术上是 3.6+),其中字典按插入顺序排列,您就可以创建一个按排序顺序排列的新字典。

my_dictionary = {'abc':'123', 'def':'456', 'ABC':'123', 'Abc':'123', 'DEF':'456', 'Def':'456'}
sorted_dict = {key: my_dictionary[key] for key in sorted(my_dictionary.keys())}
print(sorted_dict)

Output: Output:

{
  "ABC": "123",
  "Abc": "123",
  "DEF": "456",
  "Def": "456",
  "abc": "123",
  "def": "456"
}

-- Edit -- - 编辑 -

Alternatively you can use items() with a sort key such as:或者,您可以将items()与排序键一起使用,例如:

my_dictionary = {'abc':'123', 'def':'456', 'ABC':'123', 'Abc':'123', 'DEF':'456', 'Def':'456'}
sorted_dict = dict(sorted(my_dictionary.items(), key=lambda x: x[0]))
print(sorted_dict)

You can write your own customed sort function ie:您可以编写自己的自定义排序 function 即:

def test(a,b):
    x, y = a.upper(), b.upper()
    if x < y: return True
    elif x == y:
        if a>b: return True

def mysort(x):
    n = len(x)
    for i in range(n-1):
        mn = x[i]
        ind = i
        for j in range(i,n):
            if test(x[j],mn): 
                mn = x[j]
                ind = j
        x[ind], x[i] = x[i], mn
    return x

then you could run:那么你可以运行:

{i:my_dictionary[i] for i in mysort(list(my_dictionary.keys()))}
Out[58]: 
{'abc': '123',
 'Abc': '123',
 'ABC': '123',
 'def': '456',
 'Def': '456',
 'DEF': '456'}

of course you could try你当然可以试试

 mysort(['ABC','acD','Abc','abc'])

Just note that this an implementation of the insertion sort You can implement any sorting algorithm that best suits your case.请注意,这是insertion sort的实现您可以实现最适合您的情况的任何排序算法。 Though this is not too efficient for large lists虽然这对于大型列表不是太有效

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

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