python里keys_Python 3中的dict.keys()[0]

I have this sentence:

def Ciudad(prob):

numero = random.random()

ciudad = prob.keys()[0]

for i in prob.keys():

if(numero > prob[i]):

if(prob[i] > prob[ciudad]):

ciudad = i

else:

if(prob[i] > prob[ciudad]):

ciudad = i

return ciudad

But when I call it this error pops:

TypeError: 'dict_keys' object does not support indexing

is it a version problem? I'm using Python 3.3.2

解决方案

dict.keys() is a dictionary view. Just use list() directly on the dictionary instead if you need a list of keys, item 0 will be the first key in the (arbitrary) dictionary order:

list(prob)[0]

or better still just use:

next(iter(dict))

Either method works in both Python 2 and 3 and the next() option is certainly more efficient for Python 2 than using dict.keys(). Note however that dictionaries have no set order and you will not know what key will be listed first.

It looks as if you are trying to find the maximum key instead, use max() with dict.get:

def Ciudad(prob):

return max(prob, key=prob.get)

The function result is certainly going to be the same for any given prob dictionary, as your code doesn't differ in codepaths between the random number comparison branches of the if statement.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值