Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I am attempting to figure a sorted dictionary. But the order for the items among mydict and orddict doesn't appear to change.

from collections import OrderedDict

mydict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

orddict = OrderedDict(mydict)

print(mydict, orddict)

# print items in mydict:

print('mydict')

for k, v in mydict.items():

    print(k, v)

print('ordereddict')

# print items in ordered dictionary

for k, v in orddict.items():

    print(k, v)

# print the dictionary keys

# for key in mydict.keys():

#     print(key)

#  print the dictionary values

# for value in mydict.values():

#     print(value)

1 Answer

0 votes
by (26.4k points)

An OrderedDict preserves components were inserted: 

>>> od = OrderedDict()

>>> od['c'] = 1

>>> od['b'] = 2

>>> od['a'] = 3

>>> od.items()

[('c', 1), ('b', 2), ('a', 3)]

>>> d = {}

>>> d['c'] = 1

>>> d['b'] = 2

>>> d['a'] = 3

>>> d.items()

[('a', 3), ('c', 1), ('b', 2)]

So an OrderedDict doesn't structure the elements for you, it safeguards the orders you give it. 

On the off chance that you need to "sort" a dictionary, you most likely need

>>> sorted(d.items())

[('a', 1), ('b', 2), ('c', 3)]

Want to become a expert in python? Join the python course fast!

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...