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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值