如何在python字典中按键排序

2024-09-24 20:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为data的python字典,里面有子字典,比如

data = {'ind1' : {}, 'ind10' : {}, 'ind11' : {}, 'ind12' : {}, 'ind13', 'ind14' : {}, 'ind15' : {}, 'ind16' : {}, 'ind17' : {}, 'ind18' : {}, 'ind19' : {}, 'ind2' : {}, 'ind20' : {}, 'ind3' : {}, 'ind30' : : {}, 'ind31' : {} 'ind5' : {}, 'ind6' : {}, 'ind7' : {}, 'ind8' : {}, 'ind9' : {}}

我想把字典里的数据按键排序为

^{pr2}$

我尝试从集合库中data = collections.OrderedDict(sorted(data.items()))

这就是结果

ind1 : {}
ind11 : {}
ind12 : {}
ind13 : {}
.....
ind20 : {}
ind21 : {}
....
ind3 : {}
ind4 : {}
....

请帮忙


Tags: data字典有子ind3ind1ind12ind15ind18
3条回答

您真的想在字典中对数据进行排序,还是只想对.keys()提供的列表进行排序?在

如果只对值列表排序,则此链接应包含所需内容:https://wiki.python.org/moin/HowTo/Sorting

如果你想在字典里整理数据,我很想知道为什么。我会跟进并在您回复时添加建议。在

祝你好运!在

你需要在密钥前面加上“ind”前缀吗?你可以使用整数作为键来正确排序。现在它是按字母顺序排序的,这就是问题的起因。在

如果不能,假设您的密钥遵循相同的格式,请使用以下命令进行排序:

 collections.OrderedDict(sorted(data.items(), key=lambda kv: int(kv[0][3:])))

它使用前缀后面的整数进行排序。在

如果希望“ind10”位于“ind9”之后,则需要对键使用自然排序算法;^)

来自于ActiveState的wizkid

def keynat(string):
  r'''A natural sort helper function for sort() and sorted()
  without using regular expression.

  >>> items = ('Z', 'a', '10', '1', '9')
  >>> sorted(items)
  ['1', '10', '9', 'Z', 'a']
  >>> sorted(items, key=keynat)
  ['1', '9', '10', 'Z', 'a']
  '''
  r = []
  for c in string:
     if c.isdigit():
        if r and isinstance(r[-1], int):
           r[-1] = r[-1] * 10 + int(c)
        else:
           r.append(int(c))
     else:
        r.append(c)
  return r

data = collections.OrderedDict(
  sorted(
    data.iteritems(),
    key=lambda row:keynat(row[0])
  )
)

相关问题 更多 >