【问题标题】:Reverse a dictionary order python [closed]反转字典顺序python [关闭]
【发布时间】:2012-08-08 13:12:56
【问题描述】:

我有一个python字典如下:

DictValue = {
'Event1': {},
'Event2': {
    'copy3': {
        'SourcePath': 'souce3',
        'DestPath': 'dest3',
        'Platform': u 'Debug|Win32'
    },
    'copy2': {
        'SourcePath': 'souce3',
        'DestPath': 'dest2',
        'Platform': u 'Debug|Win32'
    },
    'copy1': {
        'SourcePath': 'souce1',
        'DestPath': 'dest1',
        'Platform': u 'Debug|x64'
    },
    'copy5': {
        'SourcePath': 'souce5',
        'DestPath': 'dest5',
        'Platform': u 'Release|Win32'
    },
    'copy4': {
        'SourcePath': 'souce4',
        'DestPath': 'dest4',
        'Platform': u 'Release|x64'
    }
}
}

我想对 Dictionary 值进行排序,使其看起来像

{
'Event1': {},
'Event2': {
    'copy1': {
        'SourcePath': 'souce1',
        'DestPath': 'dest1',
        'Platform': u 'Debug|Win32'
    },
    'copy2': {
        'SourcePath': 'souce2',
        'DestPath': 'dest2',
        'Platform': u 'Debug|Win32'
    },
    'copy3': {
        'SourcePath': 'souce3',
        'DestPath': 'dest3',
        'Platform': u 'Debug|x64'
    },
    'copy4': {
        'SourcePath': 'souce4',
        'DestPath': 'dest4',
        'Platform': u 'Release|Win32'
    },
    'copy5': {
        'SourcePath': 'souce5',
        'DestPath': 'dest5',
        'Platform': u 'Release|x64'
    }
}
​}

有可能吗?请帮忙。我正在使用python 2.6

谢谢。

【问题讨论】:

    标签: python python-2.6


    【解决方案1】:

    字典没有任何排序。如果您需要订购,您的选择是:

    • 改为使用元组列表。
    • 循环时对.keys() 进行排序(或.values().items(),取决于您的需要)
    • 请改用OrderedDict

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 2019-09-18
      • 2023-03-18
      • 2015-11-13
      • 1970-01-01
      • 2020-06-30
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多