简体   繁体   English

在python中反转dict并访问其值的正确方法是什么?

[英]What is the correct way to reverse dict and access its values in python?

While the following code perfectly prints out c , b , a mypy complains about it. 尽管以下代码完美地打印了cba mypy抱怨它。

main.py:10: error: No overload variant of "reversed" matches argument types [typing.ValuesView[builtins.str*]]

What is the correct way to traverse x in reverse order and get the values? 以相反的顺序遍历x并获取值的正确方法是什么?

from collections import OrderedDict

def main() -> None:
    x = OrderedDict([
        (1, 'a'),
        (2, 'b'),
        (3, 'c'),
    ])

    for y in reversed(x.values()):
        print(y)


if __name__ == '__main__':
    main()

This is because the OrderedDict dictionary views do implement __reversed__ but do not inherit from collections.abc.Reversible (the values view does inherit from collections.abc.ValuesView ). 这是因为OrderedDict字典视图确实实现了__reversed__但没有继承自collections.abc.Reversible (值视图确实继承自collections.abc.ValuesView )。

This could be fixed both by adding that base class in the Python standard library, and by updating the Python Typeshed definition . 可以通过在Python标准库中添加该基类以及通过更新Python Typeshed定义来解决此问题 I've filed an issue with the latter , as that's the faster method to get you a fix. 我已经针对后者提出了问题 ,因为这是为您提供修复的更快方法。

You can clone my pull-request branch to get the new definitions locally, then use the --custom-typeshed-dir switch to mypy to use it over the one compiled into mypy itself: 您可以克隆我的pull-request分支以在本地获取新的定义,然后使用--custom-typeshed-dir切换到mypy以将其用于编译成mypy本身的分支:

git clone https://github.com/mjpieters/typeshed.git \
    --branch ordereddict_views_reversible \
    ~/typeshed_ordereddict_views_reversible   # or a different location
mypy --custom-typeshed-dir ~/typeshed_ordereddict_views_reversible <yourproject>

While it works on Python 3.6, on previous versions of Python 3, your code doesn't work. 虽然它可以在Python 3.6上运行,但在Python 3的早期版本中却无法使用。 on python 3.4: 在python 3.4上:

TypeError: argument to reversed() must be a sequence

(has to do with the type of dict.values() ) (与dict.values()的类型有关)

One workaround is to convert to list first but that's wasteful. 一种解决方法是先转换为list但这很浪费。

for y in reversed(list(x.values())):
    print(y)

mypy isn't aware of that novelty (yet) and issues an error. mypy尚未意识到这种新颖性,并发出了错误。

You should ignore that error. 您应该忽略该错误。 I didn't try it but maybe commenting with # type: ignore works (discussed in https://github.com/python/mypy/issues/500 ): 我没有尝试过,但是也许用# type: ignore注释# type: ignore工作(在https://github.com/python/mypy/issues/500中讨论):

for y in reversed(list(x.values())):  # type: ignore

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

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