Vijay Kalmath
Vijay Kalmath

Reputation: 178

Difference in syntax of a normal dictionary and OrderedDictonary

The syntax of printing a normal dictionary is

{'a': 1, 'c': 3, 'b': 2}

Whereas

The syntax of printing a OrderedDict is

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

Is there any way where i can print/return the OrderedDict in the Normal Dictionary way??

Upvotes: 2

Views: 104

Answers (3)

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

The easy way:

from collections import OrderedDict

a = {'a': 1, 'c': 3, 'b': 2}
new_dict = dict(OrderedDict(a))
print(new_dict)
print(type(new_dict))

Output:

{'a': 1, 'c': 3, 'b': 2}
<type 'dict'>

The hard way:

You can also return the OrderedDict to a simple dict using groupby from itertools module like this way:

from collections import OrderedDict
from itertools import groupby
a = {'a': 1, 'c': 3, 'b': 2}

new_dict = {key:list(val)[0][1] for key, val in groupby(OrderedDict(a).items(), lambda x : x[0])}
print(new_dict)
print(type(new_dict))

Output:

{'c': 3, 'a': 1, 'b': 2`}
<type 'dict'>

Edit:

I see that there is some downvotes because they think that the output should be an ordered string. So, this is how do deal with it:

from collections import OrderedDict

a = {'a': 1, 'c': 3, 'b': 2}
new_dict = OrderedDict(a)

b = "{%s}" % ", ".join([str(key)+":"+str(val) for key, val in sorted(new_dict.iteritems())])

print(b)
print(type(b))

Output:

{'a':1, 'b':2, 'c':3}
<type 'str'>

Upvotes: 0

KromviellBlack
KromviellBlack

Reputation: 918

To print OrderedDict in a dict-way you can act like this (of course, if the actual order of the items does not matter to print):

def some_function():
    d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
    od = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
    return od

my_ordered_dict_variable = some_function()
print('My Ordered Dicdict:', dict(my_ordered_dict_variable))

This code will print:

{'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

Upvotes: 0

mguijarr
mguijarr

Reputation: 7908

Use a custom __str__ method in your own OrderedDict class ; in the custom method, you can build the string you want:

from collections import OrderedDict

class MyOrderedDict(OrderedDict):
   def __str__(self):
      return "{%s}" % ", ".join([repr(k)+": "+str(v) for k, v in self.iteritems()])

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

Upvotes: 3

Related Questions