如何在Python中实现关联数组(而不是字典)? [英] How to implement associative array (not dictionary) in Python?
问题描述
我想在Python中打印一本字典:
I trying to print out a dictionary in Python:
Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.iteritems():
print Key,"=",Value
虽然项目Forename是首先列出的,但Python 中的字典似乎按照值排序,所以结果是这样的:
Although the item "Forename" is listed first, but dictionaries in Python seem to be sorted by values, so the result is like this:
Surname = Dinh
Forename = Paul
如何在代码中以相同的顺序打印出这些内容,或在中附加项目时的顺序(不按值或按键分类)?
How to print out these with the same order in code or the order when items are appended in (not sorted by values nor by keys)?
推荐答案
您可以使用元组列表(或列表列表)。如下:
You can use a list of tuples (or list of lists). Like this:
Arr= [("Forename","Paul"),("Surname","Dinh")]
for Key,Value in Arr:
print Key,"=",Value
Forename = Paul
Surname = Dinh
您可以使用以下语言制作字典:
you can make a dictionary out of this with:
Dictionary=dict(Arr)
正确排序的键如下所示:
And the correctly sorted keys like this:
keys = [k for k,v in Arr]
然后这样做:
for k in keys: print k,Dictionary[k]
但我同意您的问题的意见:将键的排序是不容易的
but I agree with the comments on your question: Would it not be easy to sort the keys in the required order when looping instead?
编辑:(谢谢Rik Poggi), OrderedDict 为你做这个:
(thank you Rik Poggi), OrderedDict does this for you:
od=collections.OrderedDict(Arr)
for k in od: print k,od[k]
这篇关于如何在Python中实现关联数组(而不是字典)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!