日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python versions compatibility_为什么在python中迭代一个字典时必须调用.iteritems()?...

發布時間:2025/3/20 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python versions compatibility_为什么在python中迭代一个字典时必须调用.iteritems()?... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Why do you have to call iteritems() to iterate over key, value pairs in a dictionary? ie

dic = {'one':'1', 'two':'2'}

for k, v in dic.iteritems():

print k, v

Why isn't that the default behavior of iterating over a dictionary

for k, v in dic:

print k, v

解決方案

For every python container C, the expectation is that

for item in C:

assert item in C

will pass just fine -- wouldn't you find it astonishing if one sense of in (the loop clause) had a completely different meaning from the other (the presence check)? I sure would! It naturally works that way for lists, sets, tuples, ...

So, when C is a dictionary, if in were to yield key/value tuples in a for loop, then, by the principle of least astonishment, in would also have to take such a tuple as its left-hand operand in the containment check.

How useful would that be? Pretty useless indeed, basically making if (key, value) in C a synonym for if C.get(key) == value -- which is a check I believe I may have performed, or wanted to perform, 100 times more rarely than what if k in C actually means, checking the presence of the key only and completely ignoring the value.

On the other hand, wanting to loop just on keys is quite common, e.g.:

for k in thedict:

thedict[k] += 1

having the value as well would not help particularly:

for k, v in thedict.items():

thedict[k] = v + 1

actually somewhat less clear and less concise. (Note that items was the original spelling of the "proper" methods to use to get key/value pairs: unfortunately that was back in the days when such accessors returned whole lists, so to support "just iterating" an alternative spelling had to be introduced, and iteritems it was -- in Python 3, where backwards compatibility constraints with previous Python versions were much weakened, it became items again).

總結

以上是生活随笔為你收集整理的python versions compatibility_为什么在python中迭代一个字典时必须调用.iteritems()?...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。