David542
David542

Reputation: 110382

Get sorted dict values

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?

Upvotes: 1

Views: 78

Answers (2)

Eugene Soldatov
Eugene Soldatov

Reputation: 10145

Use sorted keys:

d = {'first': 'asdf', 'second': 'aaaa'}
values = [d[x] for x in sorted(d)]

Upvotes: 4

David542
David542

Reputation: 110382

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']

Upvotes: 0

Related Questions