What is the difference between dict.items() and dict.iteritems() in Python2?

后端 未结 10 698
天命终不由人
天命终不由人 2020-11-22 08:10

Are there any applicable differences between dict.items() and dict.iteritems()?

From the Python docs:

dict.items(): Return a

10条回答
  •  無奈伤痛
    2020-11-22 08:32

    If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:

    DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))
    

    Use it like this:

    for key, value in DICT_ITER_ITEMS(myDict):
        # Do something with 'key' and/or 'value'.
    

提交回复
热议问题