返回特定索引号的所有值

时间:2015-10-20 13:50:29

标签: python list dictionary

例如,从这本词典中:

dictionary = {"one":["a","b"],"two":["c","d"],"three":["e","f"]}

我想返回索引1处的所有值:("b", "d", "f")

这可能吗?

2 个答案:

答案 0 :(得分:4)

您可以使用dict.values

>>> d =  {"one":["a","b"],"two":["c","d"],"three":["e","f"]}
>>> [i[1] for i in d.values()]
['f', 'd', 'b']

但是由于字典不维护顺序,列表将不按顺序排列。

对于这个特定的例子,sorted效果很好

>>> [i[1] for i in sorted(d.values())]
['b', 'd', 'f']

答案 1 :(得分:2)

d =  {"one":["a","b"],"two":["c","d"],"three":["e","f"]}
i = 1

[d[key][i] for key in sorted(d) if len(d[key]) > i]