如何在Python中创建OrderedDict? [英] How to create an OrderedDict in Python?

查看:61
本文介绍了如何在Python中创建OrderedDict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试维护Python字典的顺序,因为本机dict没有任何顺序. SE中的许多答案建议使用OrderedDict.

I tried to maintain the order of a Python dictionary, since native dict doesn't have any order to it. Many answers in SE suggested using OrderedDict.

from collections import OrderedDict

domain1 = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }

domain2 = OrderedDict({ "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  })

print domain1
print " "    
for key,value in domain1.iteritems():
    print (key,value)

print " "

print domain2
print ""
for key,value in domain2.iteritems():
    print (key,value)

迭代之后,我需要字典来保持其原始顺序并将键和值打印为原始值:

After iteration, I need the dictionary to maintain its original order and print the key and values as original:

{
    "de": "Germany",
    "sk": "Slovakia",
    "hu": "Hungary",
    "us": "United States",
    "no": "Norway"
}

不过,无论哪种方式,我都不会保留此顺序.

Either way I used doesn't preserve this order, though.

推荐答案

您需要向其传递一系列项目或按顺序插入项目-这样才能知道顺序.尝试这样的事情:

You need to pass it a sequence of items or insert items in order - that's how it knows the order. Try something like this:

from collections import OrderedDict

domain = OrderedDict([('de', 'Germany'),
                      ('sk', 'Slovakia'),
                      ('hu', 'Hungary'),
                      ('us', 'United States'),
                      ('no', 'Norway')])

该数组具有顺序,因此OrderedDict将知道您想要的顺序.

The array has an order, so the OrderedDict will know the order you intend.

这篇关于如何在Python中创建OrderedDict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆