如何在Python中实现关联数组(不是字典)?

问题描述 投票:0回答:7

我试图用Python打印出一本字典:

Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.iteritems():
  print Key,"=",Value

虽然“Forename”项被列在最前面,但Python中的字典似乎是按值排序的,所以结果是这样的:

Surname = Dinh Forename = Paul

如何在代码中以相同的顺序打印这些内容或

添加项目时的顺序(不按值或键排序)?

python sorting dictionary associative-array
7个回答
25
投票
您可以使用元组列表(或列表列表)。像这样:

Arr= [("Forename","Paul"),("Surname","Dinh")] for Key,Value in Arr: print Key,"=",Value Forename = Paul Surname = Dinh

你可以用它制作一本字典:

Dictionary=dict(Arr)

正确排序的键如下所示:

keys = [k for k,v in Arr]

然后这样做:

for k in keys: print k,Dictionary[k]

但我同意对你的问题的评论:在循环时按所需顺序对键进行排序会不会很容易?

编辑:(谢谢 Rik Poggi),OrderedDict 为您做到这一点:

od=collections.OrderedDict(Arr) for k in od: print k,od[k]
    

17
投票
尝试 OrderedDict

首先,字典根本不排序,也不按键排序,也不按值排序。

根据你的描述。您实际上需要

collections.OrderedDict 模块

from collections import OrderedDict my_dict = OrderedDict([("Forename", "Paul"), ("Surname", "Dinh")]) for key, value in my_dict.iteritems(): print '%s = %s' % (key, value)
请注意,您需要从元组列表而不是另一个字典中实例化 

OrderedDict

,因为 dict 实例将在实例化 OrderedDict 之前打乱项目的顺序。



5
投票
这可能会更好地满足您的需求:

Dictionary = {"Forename":"Paul", "Surname":"Dinh"} KeyList = ["Forename", "Surname"] for Key in KeyList: print Key, "=", Dictionary[Key]
    

3
投票
“但是Python中的字典是按值排序的”也许我错了,但是你想玩什么游戏?字典不按任何内容排序。

您将有两种解决方案,要么保留字典附加的键列表,要么使用不同的数据结构,例如一个或多个数组。


3
投票
我想知道这是否是您想要的

有序字典

>>> 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
    

0
投票
从 Python 3.7 开始,常规

dict

 保证是有序的,所以你可以这样做

Dictionary = {"Forename":"Paul","Surname":"Dinh"} for Key,Value in Dictionary.items(): print(Key,"=",Value)
    
© www.soinside.com 2019 - 2024. All rights reserved.