Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python : list of dictionary values by alphabetical order of keys

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?

like image 532
Jinx Avatar asked Dec 12 '22 06:12

Jinx


1 Answers

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.

like image 172
Martijn Pieters Avatar answered May 09 '23 16:05

Martijn Pieters