如何在Python中实现关联数组(而不是字典)?
我正在尝试用Python打印词典:如何在Python中实现关联数组(而不是字典)?,python,sorting,dictionary,associative-array,Python,Sorting,Dictionary,Associative Array,我正在尝试用Python打印词典: Dictionary = {"Forename":"Paul","Surname":"Dinh"} for Key,Value in Dictionary.iteritems(): print Key,"=",Value 虽然项目“Forename”列在第一位,但Python中的字典似乎是按值排序的,因此结果如下: Surname = Dinh Forename = Paul keys = [k for k,v in Arr] 如何以代码中相同的顺序
Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.iteritems():
print Key,"=",Value
虽然项目“Forename”列在第一位,但Python中的字典似乎是按值排序的,因此结果如下:
Surname = Dinh
Forename = Paul
keys = [k for k,v in Arr]
如何以代码中相同的顺序或项目追加到中时的顺序打印这些内容(不按值或键排序)?您可以使用元组列表(或列表列表)。像这样:
Arr= [("Forename","Paul"),("Surname","Dinh")]
for Key,Value in Arr:
print Key,"=",Value
Forename = Paul
Surname = Dinh
您可以使用以下工具制作一本词典:
Dictionary=dict(Arr)
正确排序的关键点如下:
Surname = Dinh
Forename = Paul
keys = [k for k,v in Arr]
然后这样做:
for k in keys: print k,Dictionary[k]
但我同意你对问题的评论:当循环时,按要求的顺序对密钥进行排序不是很容易吗
编辑:(谢谢Rik Poggi),订购的ICT为您完成以下任务:
od=collections.OrderedDict(Arr)
for k in od: print k,od[k]
“但是Python中的字典是按值排序的”也许我搞错了,但你认为是什么游戏?字典不是按任何东西分类的
您将有两种解决方案,或者保留字典中的附加键列表,或者使用不同的数据结构,如一个或多个数组。这可能更好地满足您的需要:
Dictionary = {"Forename":"Paul","Surname":"Dinh"}
KeyList = ["Forename", "Surname"]
for Key in KeyList:
print Key,"=",Dictionary[Key]
你可以用。它在python2.7和python3.2+中可用。首先,字典根本不按键或值排序 根据你的描述。你确实需要一个模块
请注意,您需要从元组列表而不是从另一个dict实例化
OrderedDict
,因为dict实例将在实例化OrderedDict之前洗牌项目的顺序。我想知道您想要的是有序dict:
>>> k = "one two three four five".strip().split()
>>> v = "a b c d e".strip().split()
>>> k
['one', 'two', 'three', 'four', 'five']
>>> v
['a', 'b', 'c', 'd', 'e']
>>> dx = dict(zip(k, v))
>>> dx
{'four': 'd', 'three': 'c', 'five': 'e', 'two': 'b', 'one': 'a'}
>>> for itm in dx:
print(itm)
four
three
five
two
one
>>> # instantiate this data structure from OrderedDict class in the Collections module
>>> from Collections import OrderedDict
>>> dx = OrderedDict(zip(k, v))
>>> for itm in dx:
print(itm)
one
two
three
four
five
使用OrderdDict创建的字典将保留原始插入顺序
换句话说,这样的字典根据键/值对的插入顺序对它们进行迭代
例如,当您删除一个键,然后再次添加同一个键时,迭代顺序为:
>>> del dx['two']
>>> for itm in dx:
print(itm)
one
three
four
five
>>> dx['two'] = 'b'
>>> for itm in dx:
print(itm)
one
three
four
five
two
您可以使用一个额外的键列表来确定顺序我正在考虑使用2个列表(python数组),然后使用“enumerate”,但这很复杂,您还需要能够通过键快速访问它吗?对于python中的字典,元素的顺序不能保证为任何顺序,因此您不能假设它们是按值排序的。例如-
>>>Dictionary={“Forename”:“Paul”,“姓氏”:“Daih”,“Middle”:“Zarah”}>>对于键,Dictionary.iteritems()中的值:。。。打印键“=”,值。。。Middle=Zarah lasname=Daih Forename=Paul
正如我前面提到的,字典中元素的顺序不能保证是特定的。我不确定iteritems()背后的机制是什么。是否可以使用:Arr=[[“Forename”,“Paul”],[“姓氏”,“Dinh”]?元组列表是实现OrderedDict
s的方式,如果字典是OP要寻找的结构,他应该只使用它们,避免每次转换的痛苦。但大多数时候我似乎不知道键的列表,所以你怎么知道排序:)有一种情况:假设“字典”是通过一个函数传递给我的。我想保持该函数创建的值的顺序(例如通过“append”)然后collections.OrderedDict
从lig和strcat的anwsers更适合:)这对您理解我的答案是必要的吗?事实上,我没有使用OP的样本数据有两个原因:(i)我们在这里讨论的是有序序列,OP的数据只有两个键-值对;(ii)我为示例数据选择了键和值,使读者能够轻松地看到我代码的要点——即顺序保留。因此,从Python 3.6开始,dict保持键的顺序。