Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionaries how to keep them in order

I'm thinking of dictionaries as an associative array, so when I typed

dict1 = {'first' : 1, 'second' : 2}

I was hoping when I called it it would be in the order that it was written, but it wasn't. It was 'second' before 'first'. Looked it up and found that dictionaries are unordered. So that makes sense, but I was wondering if there was a way to keep them in the same order that you wrote them (or appended)? All I'm looking for here is basically a list (which stays in order) that allows strings as a key.

Thanks

like image 654
user1159454 Avatar asked Dec 09 '22 23:12

user1159454


2 Answers

from collections import OrderedDict

OrderedDict([("first", 1), ("second", 2)])

That works in Python >= 2.7, IIRC. For earlier versions, there are replacements available on the internet, but keeping the keys around in a separate is probably the simplest workaround.

like image 144
Fred Foo Avatar answered Dec 27 '22 04:12

Fred Foo


Python has an OrderedDict (in the collections module) just for this.

New in version 2.7

like image 36
jedwards Avatar answered Dec 27 '22 05:12

jedwards