Python 获取排序的dict值

Python 获取排序的dict值,python,Python,如何基于排序键获取字典值?例如: d = { 'first': 'asdf' 'second': 'aaaa' } ==> ['asdf', 'aaaa'] 我的想法大致如下: sorted(x.item(), sort=...) 如何做到这一点?您可以使用如下列表: >>> d = { ... 'first': 'asdf', ... 'second': 'aaaa' ... } >>&g

如何基于排序键获取字典值?例如:

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

==> ['asdf', 'aaaa']
我的想法大致如下:

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

如何做到这一点?

您可以使用如下列表:

>>> d = {
...          'first': 'asdf',
...          'second': 'aaaa'
...     }
>>> [item[1] for item in sorted(d.items(), key=lambda x: x[0])]
['asdf', 'aaaa']

您可以使用如下列表:

>>> d = {
...          'first': 'asdf',
...          'second': 'aaaa'
...     }
>>> [item[1] for item in sorted(d.items(), key=lambda x: x[0])]
['asdf', 'aaaa']
使用排序键:

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

d = {'first': 'asdf', 'second': 'aaaa'}
values = [d[x] for x in sorted(d)]
无需使用
.keys()
。只需
d
即可迭代按键,无需使用
.keys()
。只需
d
就可以迭代