Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary in python with order I set at start [duplicate]

I'm making dictionary:

d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'

But when I display it I saw that this dict is reversed.

print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?

like image 622
user278618 Avatar asked Dec 20 '10 15:12

user278618


1 Answers

from collections import OrderedDict

d = OrderedDict()
d["server"] = "mpilgrim"
d["database"] = "master"
d['mynewkey'] = 'mynewvalue'

print(d)

OrderedDict([('server', 'mpilgrim'), ('database', 'master'), ('mynewkey', 'mynewvalue')])
like image 154
Aphex Avatar answered Sep 30 '22 16:09

Aphex