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
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.
Python has an OrderedDict
(in the collections module) just for this.
New in version 2.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With