我试图用Python打印出一本字典:
Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.iteritems():
print Key,"=",Value
虽然“Forename”项被列在最前面,但Python中的字典似乎是按值排序的,所以结果是这样的:
Surname = Dinh
Forename = Paul
如何在代码中以相同的顺序打印这些内容或
添加项目时的顺序(不按值或键排序)?
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]
根据你的描述。您实际上需要
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 之前打乱项目的顺序。
Dictionary = {"Forename":"Paul", "Surname":"Dinh"}
KeyList = ["Forename", "Surname"]
for Key in KeyList:
print Key, "=", Dictionary[Key]
您将有两种解决方案,要么保留字典附加的键列表,要么使用不同的数据结构,例如一个或多个数组。
有序字典:
>>> 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
dict
保证是有序的,所以你可以这样做
Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.items():
print(Key,"=",Value)