Python字典,如何保持键/值与声明相同的顺序? [英] Python dictionary, how to keep keys/values in same order as declared?

查看:167
本文介绍了Python字典,如何保持键/值与声明相同的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对Python而言,这是新的,并且有关于词典的问题。我有一个我以特定顺序宣布的字典,希望始终保持这样的顺序。键/值不能真正按照它们的价值保持顺序,我只是按照我宣布的顺序。



所以如果我有字典:

  d = {'ac':33,'gw':20,'ap':102,'za' 321,'bs':10} 

如果我查看或迭代不是这样的顺序通过它,有什么办法确保Python将保持明确的命令,我声明了键/值?



使用Python 2.6

解决方案

 从集合导入OrderedDict 
OrderedDict((word,True) b

包含

  OrderedDict([('He',True),('will',True),('be',True),('the',True),('winner',True)])

如果值为 True (或任何其他不可变对象)你也可以使用:

  OrderedDict.fromkeys(words,真的)


new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.

So if I have the dictionary:

d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}

It isn't in that order if I view it or iterate through it, is there any way to make sure Python will keep the explicit order that I declared the keys/values in?

Using Python 2.6

解决方案

from collections import OrderedDict
OrderedDict((word, True) for word in words)

contains

OrderedDict([('He', True), ('will', True), ('be', True), ('the', True), ('winner', True)])

If the values are True (or any other immutable object), you can also use:

OrderedDict.fromkeys(words, True)

这篇关于Python字典,如何保持键/值与声明相同的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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