Question

Is there a simple way of getting a list of values from a dictionary, but in the way that all values are ordered by alphabetical order of keys in dictionary?

Was it helpful?

Solution

You have several options; the easiest is to just sort the items, picking out the values with a list comprehension:

[v for k, v in sorted(dictionary.iteritems())]

as tuples are sorted lexicographically; by key first, then on value. Replace iteritems() with items() if you are using Python 3.

You can sort just the keys and translate those to values:

[dictionary[k] for k in sorted(dictionary)]

Demo:

>>> dictionary = {'foo': 42, 'bar': 38, 'baz': 20}
>>> [v for k, v in sorted(dictionary.iteritems())]
[38, 20, 42]
>>> [dictionary[k] for k in sorted(dictionary)]
[38, 20, 42]

Accessing keys afterwards is also the faster option:

>>> timeit.timeit('[v for k, v in sorted(dictionary.iteritems())]', 'from __main__ import dictionary')
3.4159910678863525
>>> timeit.timeit('[d[key] for key in sorted(d)]', 'from __main__ import dictionary as d')
1.5645101070404053

Yes, that's more than twice as fast to sort a small dictionary a million times.

OTHER TIPS

There are numerous ways to do that. one way is by using sorted on the dict:

>>> d = {'c': 1, 'b': 2, 'e': 3, 'a': 4}
>>> l = [d[key] for key in sorted(d)]
>>> print(l)
[4, 2, 1, 3]

Yes, for that you can use zip. Here is an example:

y = {'a': 1, 'd':4, 'h':3, 'b': 2}

a = y.keys()
b = y.values()

print [d for (c,d) in sorted(zip(a,b))]
[1, 2, 4, 3]

or simply:

print [i[1] for i in sorted(y.items())]

You can try it out here: http://repl.it/R8e

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top