Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

dictionary - How to create an OrderedDict in Python?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')])

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...