[英]python dictionary assignment not in order
I wanted to use a dictionary both with the keys and also like lists with indexing. 我想既使用带有键的字典,也想使用带有索引的列表。 but i found that assignment to an dictionary is not in order.
但是我发现分配给字典的顺序不正确。
my python script is: 我的python脚本是:
left=['E','Z','T','Y','F']
for lhs in left:
first[lhs]=set()
follow[lhs]=set()
print first
and i get the output as: 我得到的输出为:
{'E': set([])}
{'Z': set([]), 'E': set([])}
{'Z': set([]), 'E': set([]), 'T': set([])}
{'Y': set([]), 'Z': set([]), 'E': set([]), 'T': set([])}
{'Y': set([]), 'Z': set([]), 'E': set([]), 'T': set([]), 'F': set([])}
one time it's inserted at end and another time it's at the beginning. 一次是在结尾插入,另一次是在开头插入。 this made me to think that i dont know the dictionary at all.
这使我认为我根本不了解字典。 where can i know the dictionary in depth.
我在哪里可以深入了解字典。 and how can iterate through a dictionary with keys as well as with indexes.
以及如何通过键和索引遍历字典。 for this i'm using now:
为此,我现在正在使用:
for lhs in left:
print first[lhs]
this some how helps with indexing. 这对索引编制有帮助。 but is there any other method?
但是还有其他方法吗?
Use collections.OrderedDict
. 使用
collections.OrderedDict
。 It requires Python 2.7, but it remembers the order in which keys are added, rather than storing them in an arbitrary order based on the underlying hash algorithm. 它需要Python 2.7,但它会记住添加键的顺序,而不是根据基础哈希算法以任意顺序存储键。
Update: to be precise, the storage of the dict is unchanged, but the iteration is implemented with an additional data structure to provide a fixed order based on the original insertion order of the keys. 更新:确切地说,字典的存储没有改变,但是迭代是通过附加的数据结构实现的,以基于键的原始插入顺序提供固定的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.