Mis*_*rMe 0 python dictionary python-2.7
假设我有一本字典:
{"a": 1, "b": 2, "h": 55 }
Run Code Online (Sandbox Code Playgroud)
从“ b”键开始,有什么方法可以迭代字典吗?
字典没有顺序 ; 但是,如果您期望按字母顺序排序,则可以对键进行排序,然后跳过,直到使用以下命令获得'b'
键itertools.dropwhile()
:
from itertools import dropwhile
for key in dropwhile(lambda k: k != 'b', sorted(your_dictionary)):
Run Code Online (Sandbox Code Playgroud)
演示:
>>> from itertools import dropwhile
>>> d = {"a": 1, "b": 2, "h": 55 }
>>> for key in dropwhile(lambda k: k != 'b', sorted(d)):
... print key, d[key]
...
b 2
h 55
Run Code Online (Sandbox Code Playgroud)
即使您使用的是一个collections.OrderedDict()
对象(保留插入顺序),您仍然必须跳过键,直到获得“入门”键为止。
归档时间: |
|
查看次数: |
107 次 |
最近记录: |