如何在 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屋!