Avic
Avic

Reputation: 469

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)

Upvotes: 2

Views: 9026

Answers (2)

yoonghm
yoonghm

Reputation: 4655

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.

Upvotes: 3

Andrej Shulaev
Andrej Shulaev

Reputation: 58

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

Upvotes: 2

Related Questions