1

How would I get the dictionary values based on the sorted key? For example:

d = {
     'first': 'asdf'
     'second': 'aaaa'
}

==> ['asdf', 'aaaa']

I was thinking something along the lines of:

sorted(x.item(), sort=...)

How would this be done?

David542
  • 104,438
  • 178
  • 489
  • 842
  • Possible duplicate of [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – yurib Oct 09 '15 at 18:45

2 Answers2

4

Use sorted keys:

d = {'first': 'asdf', 'second': 'aaaa'}
values = [d[x] for x in sorted(d)]
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
0

You can use a list comprehension like so:

>>> d = {
...          'first': 'asdf',
...          'second': 'aaaa'
...     }
>>> [item[1] for item in sorted(d.items(), key=lambda x: x[0])]
['asdf', 'aaaa']
David542
  • 104,438
  • 178
  • 489
  • 842