我有一个字典,我以特定的顺序声明,并希望一直保持这个顺序。键/值不能根据它们的值来排列顺序,我只想让它按照我声明它的顺序排列。
如果我有字典
d = {'ac': 33, 'gw': 20, 'ap': 102, 'za': 321, 'bs': 10}
如果我查看或遍历它,它就不是这个顺序了。是否有任何方法确保Python将保持我声明键/值的显式顺序?
我有一个字典,我以特定的顺序声明,并希望一直保持这个顺序。键/值不能根据它们的值来排列顺序,我只想让它按照我声明它的顺序排列。
如果我有字典
d = {'ac': 33, 'gw': 20, 'ap': 102, 'za': 321, 'bs': 10}
如果我查看或遍历它,它就不是这个顺序了。是否有任何方法确保Python将保持我声明键/值的显式顺序?
当前回答
你可以做和我为字典做的一样的事情。
创建一个列表和空字典:
dictionary_items = {}
fields = [['Name', 'Himanshu Kanojiya'], ['email id', 'hima@gmail.com']]
l = fields[0][0]
m = fields[0][1]
n = fields[1][0]
q = fields[1][1]
dictionary_items[l] = m
dictionary_items[n] = q
print dictionary_items
其他回答
我将给出一个简单的例子,而不是解释理论部分。
>>> from collections import OrderedDict
>>> my_dictionary=OrderedDict()
>>> my_dictionary['foo']=3
>>> my_dictionary['aol']=1
>>> my_dictionary
OrderedDict([('foo', 3), ('aol', 1)])
>>> dict(my_dictionary)
{'foo': 3, 'aol': 1}
当我试图弄清楚如何让OrderedDict工作时,我偶然发现了这篇文章。PyDev for Eclipse根本找不到OrderedDict,所以我最终决定用字典的键值创建一个元组,因为我希望它们是有序的。当我需要输出我的列表时,我只是遍历元组的值,并将元组中的迭代'key'插入字典中,以按照我需要的顺序检索我的值。
例子:
test_dict = dict( val1 = "hi", val2 = "bye", val3 = "huh?", val4 = "what....")
test_tuple = ( 'val1', 'val2', 'val3', 'val4')
for key in test_tuple: print(test_dict[key])
这有点麻烦,但我时间紧迫,这是我想出的变通办法。
注意:其他人建议的列表的列表方法对我来说并没有真正的意义,因为列表是有序和索引的(并且也是与字典不同的结构)。
另一种替代方法是使用Pandas数据框架,因为它保证了类字典结构中条目的顺序和索引位置。
从Python 3.6开始,标准字典类型默认保持插入顺序。
定义
d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}
将生成一个字典,其中键按源代码中列出的顺序排列。
这是通过为稀疏哈希表使用一个简单的整数数组来实现的,其中这些整数索引到另一个数组中,该数组存储键-值对(加上计算的哈希)。后一个数组恰好按插入顺序存储项,整个组合实际上比Python 3.5及以前版本中使用的实现使用更少的内存。详见Raymond Hettinger的原创文章。
在3.6中,这仍然被认为是一个实现细节;请参阅Python 3.6新增功能文档:
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).
Python 3.7将这个实现细节提升到一种语言规范,因此dict现在必须在所有与该版本或更新版本兼容的Python实现中保持顺序。请参阅BDFL的公告。从Python 3.8开始,字典也支持反向迭代。
在某些情况下,您可能仍然希望使用collections.OrderedDict()类,因为它在标准dict类型之上提供了一些额外的功能。比如是可逆的(这扩展到视图对象),并支持重新排序(通过move_to_end()方法)。
from collections import OrderedDict
list1 = ['k1', 'k2']
list2 = ['v1', 'v2']
new_ordered_dict = OrderedDict(zip(list1, list2))
print new_ordered_dict
# OrderedDict([('k1', 'v1'), ('k2', 'v2')])