python:迭代按键排序的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16710112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python: iterate over dictionary sorted by key
提问by user984003
I have a Python dictionary
我有一本 Python 字典
steps = {1:"value1", 5:"value2", 2:"value3"}
I need to iterate over this is sorted order by the key.
我需要迭代这个按键排序的顺序。
I tried this:
我试过这个:
x = sorted(steps, key=lambda key: steps[key])
but the values are gone from x.
但值从 x 消失了。
采纳答案by Dmitry Zagorulkin
I need to iterate over this is sorted order by the key.
我需要迭代这个按键排序的顺序。
I think lambdasis overkill here, try this:
我认为lambdas这里有点矫枉过正,试试这个:
>>> steps = {1:"val1", 5:"val2", 2:"val3"}
>>>
>>> for key in sorted(steps):
... print steps[key]
...
val1
val3
val2
回答by Ashwini Chaudhary
You need to iterate over steps.items(), because an iteration over dict only returns its keys.
您需要迭代steps.items(),因为对 dict 的迭代仅返回其键。
>>> x = sorted(steps.items())
>>> x
[(1, 'value1'), (2, 'value3'), (5, 'value2')]
Iterate over sorted keys:
迭代排序的键:
>>> for key in sorted(steps):
... # use steps[keys] to get the value
回答by Achim
Depending on your use case, it might be an option to hold an already ordered dictionary. See pythons OrderedDictfor details. If you want to sort the keys as integer, you have to convert them to integers. The best moment to do so depends on your use case.
根据您的用例,可以选择保存已排序的字典。有关详细信息,请参阅 python OrderedDict。如果要将键排序为整数,则必须将它们转换为整数。这样做的最佳时机取决于您的用例。
回答by GrantJ
You can also use one of Python's many SortedDict container types. These types automatically maintain the dictionary sorted in key-order. Take a look at the sortedcontainersmodule which is pure-Python and fast-as-C-implementations. There's a performance comparisonthat benchmarks several other implementations against each other.
您还可以使用 Python 的许多 SortedDict 容器类型之一。这些类型自动维护按键顺序排序的字典。看看sortedcontainers模块,它是纯 Python 和 fast-as-C 实现。有一个性能比较,可以对其他几个实现进行基准测试。
In your case then, you'd use:
在你的情况下,你会使用:
from sortedcontainers import SortedDict
steps = SortedDict({1:"value1", 5:"value2", 2:"value3"})
# Then iterate the items:
for key, value in steps.items():
print key, value
# Or iterate the values:
for value in steps.values():
print value
Iteration for keys/values/items works automatically by sorted key order.
键/值/项目的迭代按排序的键顺序自动工作。
回答by Angelos
Like pointed by Zagorulkin Dmitry, you should not pass a lambda to the sorting function. The sorting function default behaviour is to act on the keys.
就像 Zagorulkin Dmitry 指出的那样,您不应该将 lambda 传递给排序函数。排序函数的默认行为是作用于键。
steps = {1:"val1", 5:"val2", 2:"val3"}
for key in sorted(steps):
print steps[key]
...
val1
val3
val2
However, passing the lambda to the sorting function isn't a better operation of small benefit (i.e. an 'overkill'), but it is actually undesired. It makes the code less readable and it also slower, particularly if you are going to apply it to very large dictionaries or make the call multiple times. Other than making the sorting target more explicit in respect to the (key, value) pairs, there is no benefit to using it. The following timings show the performance hit you get when specifying a lambda.
然而,将 lambda 传递给排序函数并不是一个好处很小的更好的操作(即“过度杀伤”),但它实际上是不受欢迎的。它降低了代码的可读性,而且速度也变慢了,尤其是当您要将其应用于非常大的字典或多次调用时。除了使排序目标在 (key, value) 对方面更加明确之外,使用它没有任何好处。以下时间显示了指定 lambda 时获得的性能影响。
steps = {randint(0, 100000): randint(0, 100000) for _ in range(100000) } # random dict
%%timeit
sort_list = [value for _, value in sorted(steps.items(), key=lambda item: item[0])]
1 loops, best of 3: 241 ms per loop
%%timeit
sort_list = [steps[k] for k in sorted(steps, key=lambda k: k)]
1 loops, best of 3: 196 ms per loop
%%timeit
sort_list = [ steps[key] for key in sorted(steps) ]
10 loops, best of 3: 106 ms per loop
回答by David Schumann
In case your keys are not integers, but strings that should be parsed as integers:
如果您的键不是整数,而是应解析为整数的字符串:
steps = {'1':'value1', '10': 'value0', '5':'value2', '2':'value3'}
you can use something similar to your solution:
您可以使用类似于您的解决方案的东西:
for key in sorted(steps, key=lambda key: int(key)):
print(key, steps[key])
1
2
5
10

