Python 3 dict behavior in Python 2

前端 未结 1 1128
陌清茗
陌清茗 2021-01-29 05:48

I saw this question tonight. I had never heard of future_builtins before this, and it got me wondering. future_builtins only covers a few types, and

相关标签:
1条回答
  • 2021-01-29 06:23

    You can use viewkeys(), viewitems() and viewvalues() in py2x.

    >>> dict.viewkeys?
    Type:       method_descriptor
    String Form:<method 'viewkeys' of 'dict' objects>
    Namespace:  Python builtin
    Docstring:  D.viewkeys() -> a set-like object providing a view on D's keys
    

    What’s New In Python 3.0 :

    • dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).
    • Also, the dict.iterkeys(), dict.iteritems() and dict.itervalues() methods are no longer supported.

    Bug : Backport dictviews to 2.7:

    After talking to Guido, got rid of the future import magic in favour of just providing viewkeys, viewitems and viewvalues methods of dicts. This makes efficient 2.6-and-3.0 dict-using code possibly by making 2to3 translate the view-methods directly to keys/values/items in 3.0, and not wrapping everything in list().

    2to3 tool:

    RefactoringTool: Refactored so.py
    --- so.py   (original)
    +++ so.py   (refactored)
    @@ -1 +1 @@
    -print dic.viewkeys()
    +print(dic.keys())
    
    0 讨论(0)
提交回复
热议问题