10

When i declare a list 1,2,3,4 and i do something with it , even just print i get back the same sequence 1,2,3,4.

But when i do anything with dictionaries , they always change number sequence , like it is being sorted in a twisted way i can't understand .

test1 = [4,1,2,3,6,5]
print test1
test2 = {"c":3,"a":1,"b":2,"d":4}
print test2 

[4, 1, 2, 3, 6, 5]
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

How in the world did 'a' become the first element and 'c' , even if it alphabetically sorted the dictionary it should have been 1,2,3,4 or a,b,c,d not 1,3,2,4 . wT?F @!$!@$#@!

So how do i print , get values from dictionary without changing the positions of the elements .?

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
Viktor
  • 580
  • 2
  • 14
  • 29
  • 1
    Why do you care about the order in which your dictionary keys are kept? "It's best to think of a dictionary as an [unordered](http://docs.python.org/tutorial/datastructures.html#dictionaries) set of *key: value* pairs, with the requirement that the keys are unique (within one dictionary)." – nmichaels May 19 '11 at 16:05
  • 1
    I care because i need exact sequence to display some things on my web , and it was a very convenient way to do with , `for keys, values in dict.items()`. Now it's about to become not very pretty solution , as dictionaries go out of the picture. – Viktor May 19 '11 at 16:14
  • 1
    AFAIK, no language that has associative-arrays maintains insertion order by default. It's not a great idea because there are several behaviors that are arbitrary (what happens on over-write, what happens on delete and re-insert). – Michael Lorton May 19 '11 at 18:05
  • possible duplicate of [How do you retrieve items from a dictionary in the order that they're inserted?](http://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted) – nbro Jan 10 '15 at 01:52
  • I'm from the future. They are now (on Python 3.7+ and CPython 3.6+). – Boris Verkhovskiy Mar 23 '19 at 18:45

6 Answers6

12

Dictionaries in Python are unordered by definition. Use OrderedDict if you need the order in which values were inserted (it's available in Python 2.7 and 3.x).

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 1
    I dont need sorted dictionary . I need to get the same sequence when i print the dictionary , not some weird one (sorted or i dont know). – Viktor May 19 '11 at 15:54
  • 1
    Perhaps you need to consider other collection types besides dictionary? – asawyer May 19 '11 at 15:55
  • 2
    Viktor you have to maintain the sort yourself or insert it into a sorted dictionary (which will maintain the order of insertion). You cannot have a 'normal' dictionary maintain sort order. And yes, if you rely on the order, it is 'sorted' even if you can't define the sorting algorithm. – Henry May 19 '11 at 15:56
  • For this functionality, you should keep a list that maintains the order of your keys. If you want your dict entries sorted in the order they were inserted, append the key to your key list. Then when you need to get values in-order from your dict, do something like [ my_dict[key] for key in ordered_key_list ] – dusktreader May 19 '11 at 16:02
  • >.< thx . Now i get the whole absurd thing . I am just irritated after wasting 40 minutes of my life figuring , why the hell it doesn't do what i expect it too . – Viktor May 19 '11 at 16:04
  • Google is really good for this -- not that you shouldn't ask here, but "python dictionary order" gives you a good answer and saves your 40 mins. – bluepnume May 19 '11 at 16:20
  • @Viktor Relax. It's a language you're just learning. Everyone gets surprised by features in a new language. And 40 minutes isn't really that long. – Steven Rumbalski May 19 '11 at 16:26
  • Sure . Trust me i googled , but i kind of googled for the wrong thing. I was looking for why they get sorted . Even after the Eli Bendersky answer , that dictionaries are unsorted , it made no sense for me. 40 minutes isn't that long , if it is only 40 minutes :D, but there was another half day for doing things before i got stuck and angry with dictionaries for 40 minutes . – Viktor May 19 '11 at 16:33
  • @Viktor: 40 minutes? The Lyf so Short; the Craft so Long to Lerne :-) – Eli Bendersky May 19 '11 at 16:47
  • 1
    @Viktor -- they say it takes 5000 - 10,000 hours to completely learn a skill. Python is one of the better (easier to learn) languages, but become a programmer takes at least five years. 40 minutes more or less is not going to make a difference. – Michael Lorton May 19 '11 at 18:07
  • @ Eli Bendersky @Malvolio I agree with you both =). Just got a little bit frustrated after a hard long day.And dictionaries had me killed. LOL Never thought that this question would become such a forum :D. Thank you for all the help . Really appreciated. – Viktor May 20 '11 at 01:10
2

dictionary sort order is undefined! Do not rely on it for anything. Look for a sorted dictionary if you really want a sorted dictionary, but usually you don't need one.

Examples:

  • python 2.7, it's built in to the collections module
  • Django has a SortedDict shipped with it
  • 2.4-2.7 you can use the ordereddict module, you can pip install or easy_install it
Henry
  • 6,502
  • 2
  • 24
  • 30
2

Before you get so angry and frustrated, perhaps you should read about what a dictionary actually is and how it works:

http://docs.python.org/library/stdtypes.html#mapping-types-dict

Python dicts use a hash table as the underlying storage mechanism. That means that a hash key is generated from the key that you provide. There are no guarantees about ordering with these hash keys. The entries in a dictionary are fetched in sequential order of their location in the underlying hash table when you request values(), keys(), or items().

The advantage of using a hash table is that it is extremely fast. Unlike the map class from c++ which uses a red-black tree storage mechanism ( which is sorted by the raw keys ), a hash table doesn't constantly need to be restructured to keep it efficient. For more on hash tables, see:

http://en.wikipedia.org/wiki/Hash_table

Like the other posters have said, look up OrderedDict if you need to have a key-sorted dictionary.

Good Luck!

dusktreader
  • 3,845
  • 7
  • 30
  • 40
  • For folks revisiting this thread in modern times, please note that as of python 3.6 dictionaries retain the order in which elements were inserted. – dusktreader Nov 07 '18 at 17:28
1

Clearly you know about lists. You can ask for the element at the ith index of a list. This is because lists are ordered.

>>> [1,2,3,4] == [1,4,3,2]
False

In this context, you can think of dictionaries, but where the index is the key. Therefore, two dictionaries are equal if the corresponding values of all keys in both dictionaries are the same (if one dictionary has keys that the other doesn't, then the two are not equal). Thus:

>>> {1:'a', 2:'b'} == {2:'b', 1:'a'}
True

Further Trivia

A dictionary does something called hashing on the keys of the dictionary so that when you ask for the value at a particular key (index), it can retrieve this value faster.

Hope this helps

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • That's not trivia. Understanding of hashing is vital to many tasks in software development. It's *also* useful for understanding why dictionaries aren't naturally ordered, although "They just aren't, OK?" is also a perfectly good explanation. – Michael Lorton May 20 '11 at 01:52
  • I agree that it's not trivia, but the OP seems very new to the topic, so I marked it as trivia as it probably isn't high on a prioritized list of what he wants to learn right now – inspectorG4dget May 20 '11 at 14:11
0

Dictionaries are unsorted. This is well-documented. Do not rely on the ordering of dictionaries.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

If you want to see the entries in order. something like:

test2 = {"c":3,"a":1,"b":2,"d":4}
ks = test2.keys()
ks.sort()
for key in ks:
   print key + ':' + str(test2[key])

(cut,paste, season to taste)

Andrew
  • 2,530
  • 16
  • 9