简体   繁体   English

Python:按键的前半部分/部分重新排序字典

[英]Python: Reorder a dictionary by the first half/part of the key

I need to reorder a very large OrderedDict by the first 'CSV' of its keys. 我需要通过其键的第一个“CSV”重新排序非常大的OrderedDict。 For example I have a dictionary like this: 例如,我有一个这样的字典:

 a = {'40,70': AAAAAA, '0,12': XXXXXXXX, '20,38': YYYYY}

I need it to be ordered on the first number of the key which is always two numbers separated by a comma (I need the second number to then be the ordering factor). 我需要在键的第一个数字上排序,它总是用逗号分隔的两个数字(我需要第二个数字然后是排序因子)。 The values or Letters are currently of no importance. 目前,价值或信件并不重要。 I need it to be like this: 我需要它像这样:

b = {'0,12': XXXXXXXX, '20,38': YYYYY, '40,70': AAAAAA}

The dictionary is too big to split each key in a loop - Is there a faster way of doing this? 字典太大,无法在循环中拆分每个键 - 有更快的方法吗? I have tried to make this as clear as possible. 我试图尽可能清楚地说明这一点。

Thanks. 谢谢。

you can use ordered dict to reorder the dict 你可以使用有序的dict重新排序字典

from collections import OrderedDict  
OrderedDict(sorted(a.items(), key=lambda ele:[int(item) for item in ele[0].split(',')])) 

best way would be to create tuple keys in your dictionary, then sort using natural order. 最好的方法是在字典中创建tuple键,然后使用自然顺序排序。

If you want to keep the keys as strings, then sort the items of the dictionary into a tuple, with a key function converting the key as a tuple of integers. 如果要将键保存为字符串,则将字典中的项目排序为元组,并使用键函数将键转换为整数元组。 This provides a tiebreaker in case 2 first numbers are equal: 在第一个数字相等的情况下,这提供了一个决胜局:

a = {'40,70': "AAAAAA", '0,12': "XXXXXXXX", '0,10': "XXXXXXXX", '20,38': "YYYYY"}

import collections

b = collections.OrderedDict(sorted(a.items(),key = lambda e : tuple(map(int,e[0].split(",")))))

print(b)

result: 结果:

OrderedDict([('0,10', 'XXXXXXXX'), ('0,12', 'XXXXXXXX'), ('20,38', 'YYYYY'), ('40,70', 'AAAAAA')])

第二个号码作为决胜局:

ordered_dict = dict(sorted(a.items(), key=lambda x: [int(x[0].split(",")[0]), int(x[0].split(",")[1])]))

I think using OrderedDict you can use something like this. 我认为使用OrderedDict你可以使用这样的东西。 I am not sure if this is the fastest way. 我不确定这是否是最快的方法。

To sort numerically, I assumed you will always get an integer before comma. 为了按数字排序,我假设你总是在逗号之前得到一个整数。

To use second part as second key, and turned the key to a tuple. 使用第二部分作为第二个键,并将键转换为元组。

from collections import OrderedDict
a = {'40,70': 'AAAAAA', '0,12': 'XXXXXXXX', '20,38': 'YYYYY', '0,38': 'AAYY'}
b = OrderedDict(sorted(a.items(), key=lambda x: (int(x[0].split(',')[0]), int(x[0].split(',')[1]))))
print(b)

result is 结果是

OrderedDict([('0,12', 'XXXXXXXX'), ('0,38', 'AAYY'), ('20,38', 'YYYYY'), ('40,70', 'AAAAAA')])

Use OrderedDict 使用OrderedDict

from collections import OrderedDict

a = {'40,70': 'AAAAAA', '0,12': 'XXXXXXXX', '20,38': 'YYYYY'}

b = OrderedDict(sorted(a.items()))

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

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