如何使用python按我给定的顺序对字典键进行排序

时间:2019-01-17 06:33:51

标签: python-2.7 dictionary

这是我的示例程序,我想按实际顺序打印字典项。但是我排序意味着它采用字母顺序,并且我无法在文本编辑中以相同的行打印::请帮助我。谢谢。

下面是我的代码:

import sys
from PyQt4 import QtGui

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.data ={'12345':{"Name": "k.Sudha Rani","Address":"Mysore Road 3rd line", "Pincode":"522896","City":"Bangalore","State":"Karnataka"}}

        self.initUI()

    def initUI(self):
        self.vbox = QtGui.QVBoxLayout()
        self.search_edit = QtGui.QLineEdit()
        self.text_edit = QtGui.QTextEdit()
        self.vbox.addWidget(self.search_edit)
        self.vbox.addWidget(self.text_edit)
        self.setGeometry(300, 300, 800, 500)
        self.setWindowTitle('Absolute')
        self.setLayout(self.vbox)
        self.show()
    def keyPressEvent(self, event):
        print "clickeddd"
        if event.key() == QtCore.Qt.Key_Return:
            try:
                txt =self.search_edit.text()
                self.searchitems(txt)
            except:
                pass
    def searchitems(self,txt):
        print txt, "txttttttttt"
        if str(txt) in self.data:
            ph_data = self.data[str(txt)]
            print ph_data
            for key, value in sorted(ph_data.items()):
                print key,value
                self.text_edit.append(str(key).ljust(20," ")   +" : " + value) #equal spacing all : are in same line
def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

输出除外:

Name    :   k.Sudha Rani
Address :   Mysore Road 3rd line
Pincode :   522896
City    :   Bangalore
State   :   Karnataka

2 个答案:

答案 0 :(得分:0)

一种解决方案是使用有序词典:

from collections import OrderedDict
{'12345':OrderedDict([("Name", "k.Sudha Rani"), ("Address","Mysore Road 3rd line"), ("Pincode", "522896"), ("City", "Bangalore"), ("State":"Karnataka")])}

如果您总是有nameaddresspincodecitystate,也可以从当前词典中按键调用它们

Documentation on OrderedDicts

答案 1 :(得分:0)

只需按想要的顺序将密钥存储在下面的列表中,然后遍历密钥即可。

keys_list = ['Name', 'Address', 'Pincode', 'City', 'State']
for k in keys_list:
  print(k,ph_data[k])