我完成了一项练习计划。它打印得很好,但问题是输出的最后三行是不准确的。每次我运行程序时,它会生成不同的输出,在键之间交替。我无法找到让它正确出现的方法(如程序中所述)
def main( ):
zip_dictionary = {}
zip_dictionary = update_dictionary(zip_dictionary, "CAM", "1427")
zip_dictionary = update_dictionary(zip_dictionary, "UofM", "1427")
zip_dictionary = update_dictionary(zip_dictionary, "ZIT", "1423-503")
zip_dictionary = update_dictionary(zip_dictionary, "MCOC", "1423")
zip_dictionary = update_dictionary(zip_dictionary, "NAZARETH", "1418")
zip_dictionary = update_dictionary(zip_dictionary, "OCC", "1420")
for key in zip_dictionary:
print(key, zip_dictionary[key])
for i in range(2):
print(zip_dictionary.popitem( ))
for value in zip_dictionary:
print(zip_dictionary[value], key)
def update_dictionary(dct, key, value):
dct[key] = value
return dct
main( )
答案 0 :(得分:1)
使用OrderedDict,不要打扰update_dictionary
,并且在重复key
时不要打印value
。
from collections import OrderedDict
def main( ):
zip_dictionary = OrderedDict()
zip_dictionary["CAM"] = "1427"
zip_dictionary["UofM"] = "1427"
zip_dictionary["ZIT"] = "1423-503"
zip_dictionary["MCOC"] = "1423"
zip_dictionary["NAZARETH"] = "1418"
zip_dictionary["OCC"] = "1420"
print "\nContents of dict:"
for key in zip_dictionary:
print(key, zip_dictionary[key])
print "\nPopping items:"
for i in range(2):
print(zip_dictionary.popitem( ))
print "\nRemaining items:"
for key in zip_dictionary:
print(key, zip_dictionary[key])
main( )
结果:
Contents of dict:
('CAM', '1427')
('UofM', '1427')
('ZIT', '1423-503')
('MCOC', '1423')
('NAZARETH', '1418')
('OCC', '1420')
Popping items:
('OCC', '1420')
('NAZARETH', '1418')
Remaining items:
('CAM', '1427')
('UofM', '1427')
('ZIT', '1423-503')
('MCOC', '1423')
答案 1 :(得分:0)
如果你想得到相同的'每次您可以根据字母顺序对键进行排序。
for sorted_key in [key in zip_dictionary].sort():
print(sorted_key , zip_dictionary[sorted_key])
如果他们需要按此顺序,您还可以维护带有键的有序列表。您也不需要在update_dictionary
函数中返回字典,因为它是一个可变对象。
def update_dictionary(dct, lst, key, value):
dct[key] = value
if not key in lst:
lst.append(key)
def main( ):
zip_dictionary = {}
zip_list = []
update_dictionary(zip_dictionary, zip_list, "CAM", "1427")
update_dictionary(zip_dictionary, zip_list, "UofM", "1427")
update_dictionary(zip_dictionary, zip_list, "ZIT", "1423-503")
update_dictionary(zip_dictionary, zip_list, "MCOC", "1423")
update_dictionary(zip_dictionary, zip_list, "NAZARETH", "1418")
update_dictionary(zip_dictionary, zip_list, "OCC", "1420")
for key in zip_list:
print(key, zip_dictionary[key])