简体   繁体   中英

How to sort Dictionary Keys in Python

i have this code:

myDict = {}
myDict['Hello'] = 's'
myDict['Hallo'] = 'a'
myDict['Test'] = 'b'
myDict['Buy'] = 'hoo'
myDict['Hehe'] = 'kkk'

print(list(myDict.keys()))

and it return random, like :

['Hallo','Buy','Hehe','Test,'Hello']

what I want is :

['Hello','Hallo','Test','Buy','Hehe']

'Hello' is first ,'Hallo' is second, 'Test' is Third, 'Buy' is Fourth, 'Hehe' is Fifth

it's very important because i want to make csv file :

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = list(myDict.keys())

    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ";")

    writer.writeheader()

    writer.writerow(myDict)

This is a duplicated questions:

Python 3.7+
In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.

Python 3.6 (CPython)
As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.

Python <3.6
Use the collections.OrderedDict class when you need a dict that remembers the order of items inserted.

Use OrderedDict . And just to remind you, since python 3.6 dict is insertion ordered. What version do you use ?

# regular unsorted dictionary
d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

# dictionary sorted by key
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), 
('pear', 1)]) 

# dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), 
('apple', 4)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM