简体   繁体   English

python:迭代按键排序的字典

[英]python: iterate over dictionary sorted by key

I have a Python dictionary我有一本 Python 字典

steps = {1:"value1", 5:"value2", 2:"value3"}

I need to iterate over this sorted by key.我需要迭代这个按键排序。

I tried this:我试过这个:

x = sorted(steps, key=lambda key: steps[key])

but the values are gone from x.但值从 x 消失了。

I need to iterate over this is sorted order by the key.我需要迭代这个按键排序的顺序。

I think lambdas is overkill here, try this:我认为lambdas在这里lambdas矫枉过正,试试这个:

>>> steps = {1:"val1", 5:"val2", 2:"val3"}
>>>
>>> for key in sorted(steps):
...     print steps[key]
...
val1
val3
val2

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

You can also use one of Python's many SortedDict container types.您还可以使用 Python 的许多 SortedDict 容器类型之一。 These types automatically maintain the dictionary sorted in key-order.这些类型自动维护按键顺序排序的字典。 Take a look at the sortedcontainers module which is pure-Python and fast-as-C-implementations.看看sortedcontainers模块,它是纯 Python 和 fast-as-C 实现。 There's a performance comparison that benchmarks several other implementations against each other.有一个性能比较,可以对其他几个实现进行基准测试。

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.键/值/项目的迭代按排序的键顺序自动工作。

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

Like pointed by Zagorulkin Dmitry, you should not pass a lambda to the sorting function.就像 Zagorulkin Dmitry 指出的那样,您不应该将 lambda 传递给排序函数。 The sorting function default behaviour is to act on the keys.排序函数的默认行为是作用于键。

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 (ie an 'overkill'), but it is actually undesired.然而,将 lambda 传递给排序函数并不是一个好处很小的更好的操作(即“过度杀伤”),但它实际上是不受欢迎的。 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.除了使排序目标在 (key, value) 对方面更加明确之外,使用它没有任何好处。 The following timings show the performance hit you get when specifying a lambda.以下时间显示了指定 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

Depending on your use case, it might be an option to hold an already ordered dictionary.根据您的用例,可以选择保存已排序的字典。 See pythons OrderedDict for details.有关详细信息,请参阅 python OrderedDict 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.这样做的最佳时机取决于您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM