In What Order Does Python Display Dictionary Keys

In what order does python display dictionary keys?

The order has to do with how they work internally and what order they end up in the hashtable. That in turn depends on the keys hash-value, the order they were inserted, and which Python implementation you are using.

The order is arbitrary (but not random) and it will never be useful to know which order it will be.

To get a sorted list of keys, just use sorted(D), which in your case will return ['a', 'b', 'c'].

Order of keys in dictionaries in old versions of Python

You could use OrderedDict (requires Python 2.7) or higher.

Also, note that OrderedDict({'a': 1, 'b':2, 'c':3}) won't work since the dict you create with {...} has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)]).

As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.

In what order does a dictionary in python store data?

The short answer is: in an implementation-defined order. You can't rely and shouldn't expect any particular order, and it can change after changing the dictionary in a supposedly-irrelevant manner.

Although not directly, it's somehow explained in Dictionary view objects:

Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.

Order of keys in dictionary

Dictionaries are not ordered. So there is no way to do it.

If you have python2.7+, you can use collections.OrderedDict - in this case you could retrieve the item list using .items() and then reverse it and create a new OrderedDict from the reversed list:

>>> od = OrderedDict((('a', 'first'), ('b', 'second')))
>>> od
OrderedDict([('a', 'first'), ('b', 'second')])
>>> items = od.items() # list(od.items()) in Python3
>>> items.reverse()
>>> OrderedDict(items)
OrderedDict([('b', 'second'), ('a', 'first')])

If you are using an older python version you can get a backport from http://code.activestate.com/recipes/576693/

Print original input order of dictionary in python

A regular dictionary doesn't have order. You need to use the OrderedDict of the collections module, which can take a list of lists or a list of tuples, just like this:

import collections

key_value_pairs = [('Civic86', 12.5),
('Camry98', 13.2),
('Sentra98', 13.8)]
smallestCars = collections.OrderedDict(key_value_pairs)

for car in smallestCars:
print(car)

And the output is:

Civic96
Camry98
Sentra98

How can I get the keys in a dictionary in the order that they appear in the dictionary?

Try from this source: Key Order in Python Dictionaries

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

Sadly, OrderedDict({'a': 1, 'b':2, 'c':3}) won't work because The {} has already forgotten order of the elements.

Your code would be:

Dict = OrderedDict([('Name', 'Zara'), ('Age', 7), ('Class', 'First)])

Python dictionary: are keys() and values() always the same order?

Found this:

If items(), keys(), values(),
iteritems(), iterkeys(), and
itervalues() are called with no
intervening modifications to the
dictionary, the lists will directly
correspond.

On 2.x documentation and 3.x documentation.

What ordering does dict.keys() and dict.values() guarantee?

The general rules:

  1. Before talking about what is guaranteed and what isn't, even if some ordering seems to be "guaranteed", it isn't. You should not rely on it. It is considered bad practice, and could lead to nasty bugs.
  2. d.keys(), d.values(), and d.items() all return the elements in a respective order. The order should be treated as arbitrary (no assumptions should be made about it). (docs)
  3. consecutive calls to d.keys(), d.values(), and d.items() are "stable", in the sense they are guaranteed to preserve the order of previous calls (assuming no insertion/deletion happens between the calls).
  4. Since CPython's V3.6, dict has been reimplemented, and it now preserves insertion order. This was not the goal of the change, but a side effect, and it is NOT part of the python spec, only a detail of the CPython implementation. See point #1 above: relying on this is bad practice and should not be done. Anyways, you should avoid writing CPython-specific code.
  5. In Python2, order is deterministic (i.e. creating a dict twice in the same way will result with the same order). In Python <3.6, it is no longer deterministic, so you can't rely on that either (I'm not sure if this non-determinism is part of the spec or just a CPython implementation detail).

EDIT: added point #5, thanks to @AndyHayden's comment.

How do I sort a dictionary by value?

Python 3.7+ or CPython 3.6

Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

or

>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Older Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

For instance,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

And for those wishing to sort on keys instead of values:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

In Python3 since unpacking is not allowed we can use

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])

If you want the output as a dict, you can use collections.OrderedDict:

import collections

sorted_dict = collections.OrderedDict(sorted_x)


Related Topics



Leave a reply



Submit