Python 3中的dict.keys()[0] [英] dict.keys()[0] on Python 3
问题描述
我有这句话:
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
是一个版本问题吗?我使用Python 3.3.2
is it a version problem? I'm using Python 3.3.2
推荐答案
dict.keys()
是一个字典视图。直接在字典上直接使用 list()
,如果您需要一个键列表,项0将是(任意)字典顺序中的第一个键:
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]
或更好还是只使用:
next(iter(dict))
两种方法都适用于Python 2 和 3,而 next() / code>选项对于Python 2来说比使用
dict.keys()
更有效。请注意,词典具有否设置顺序,您将不会知道将首先列出的是什么。
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.
它看起来好像是试图找到最大键,使用 max()
与 dict.get
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)
任何给定的 prob
字典,因为您的代码在如果
语句之间的随机数比较分支之间的codepaths中没有区别。
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.
这篇关于Python 3中的dict.keys()[0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!