[英]python : list of dictionary values by alphabetical order of keys
是否有一种从字典中获取值列表的简单方法,但是所有值都按字典中按字母顺序排列的方式排序?
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. 更换
iteritems()
与items()
如果你正在使用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. 是的,这对于一百万次的小字典排序速度是两倍多。
There are numerous ways to do that. 有很多方法可以做到这一点。 one way is by using
sorted
on the dict: 一种方法是使用在dict上
sorted
:
>>> 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
. 是的,为此您可以使用
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 你可以在这里试试: http : //repl.it/R8e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.