2

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)
2
  • 1
    This will work as is in Python 3.6+, otherwise use a collections.OrderedDict Commented Sep 30, 2018 at 7:13
  • 1
    Python behaves differently based on version. Commented Sep 30, 2018 at 7:28

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.