Why does the dictionary need these "iterative" methods?

Suppose it mydict

is a Python dictionary.

mydict = {'a': 1, 'b': 2}

      

I can use items

to iterate over my elements:

for k,v in mydict.items():
    print k,v

      

Or use iteritems

:

for k,v in mydict.iteritems():
    print k,v

      

who cares? I think the python philosophy is "the only way to do"?

+3


source to share


3 answers


In Python 3, methods dict.iter...()

have been removed and replaced with normal ones.

They existed when iterators were added to the language after dictionaries, so it dict.items()

returns a list. Methods have been added to dict.iter...()

allow people to create more efficient programs (like iterators are lazy), but also not break compatibility with older programs expecting a list.



Since Python 3 broke compatibility, this has been fixed. (Old usage dict.iter()

can be generated with list(dict.iter())

. Note that in Python 3 a dictionary is dict.items()

actually returned . - which can be iterated over but also provides other functionality.

+6


source


In Python 2, mydict.items

returns a new list. Usage iteritems

saves memory and is more efficient.

>>> d = dict((f, r) for f, r in zip(range(10000), reversed(range(10000))))
>>> %timeit for i in d.iteritems(): i
1000 loops, best of 3: 456 us per loop
>>> %timeit for i in d.items(): i
1000 loops, best of 3: 811 us per loop

      



But (as others have pointed out) items

remained the same in Python 2 for backward compatibility.

Python 3 fixes this problem; items

returns " view " (which is neither a list nor an iterator, but rather a "dynamic view in dictionaries of dictionaries" "that changes when the dictionary changes) and iteritems

no longer exists, and its cousins itervalues

and iterkeys

.

+4


source


I think the python philosophy is "only one way to do"?

Reason for existence items()

and iteritems()

historical:

  • Initially it only existed items()

    . He returned the list.

  • Python 2.2 introduced iteritems()

    . It returned an iterator.

  • Python 2.7 introduced viewitems()

    . It returned view .

  • Python 3 took the opportunity to tidy up the following: iteritems()

    both items()

    were dropped and viewitems()

    renamed to items()

    .

The reason iteritems()

and viewitems()

was added in 2.x, as the new features, instead of a simple replacement, items()

was to keep all 2.x versions backward compatible.

+4


source







All Articles