Python 3 上的 dict.keys()[0]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18686903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:28:03  来源:igfitidea点击:

dict.keys()[0] on Python 3

pythonpython-3.xdictionarydictview

提问by Menticolcito

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

是版本问题吗?我正在使用 Python 3.3.2

采纳答案by Martijn Pieters

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:

dict.keys()是字典视图。list()如果您需要键列表,只需直接在字典上使用,项目 0 将是(任意)字典顺序中的第一个键:

list(prob)[0]

or better still just use:

或者最好还是使用:

next(iter(dict))

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

这两种方法都适用于 Python 23,next()对于 Python 2 来说,该选项肯定比使用dict.keys(). 但是请注意,字典没有固定顺序,您将知道首先列出哪个键。

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

看起来好像您正在尝试查找最大键,请使用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 probdictionary, as your code doesn't differ in codepaths between the random number comparison branches of the ifstatement.

对于任何给定的prob字典,函数结果肯定是相同的,因为您的代码在语句的随机数比较分支之间的代码路径中没有区别if

回答by Gareth Latty

In Python 3.x, dict.keys()does not return a list, it returns an iterable (specifically, a dictionary view). It is worth noting that dictitself is also an iterable of the keys.

在 Python 3.x 中,dict.keys()不返回列表,它返回一个可迭代对象(特别是字典视图)。值得注意的是,dict它本身也是一个可迭代的键。

If you want to obtain the first key, use next(iter(dict))instead. (Note that before Python 3.6 dictionaries were unordered, so the 'first' element was an arbitrary one. Since 3.6 it will be based on insertion order. If you need that behaviour in older versions or with cross-version compatibility, you can use collections.OrderedDict).

如果要获取第一个密钥,请next(iter(dict))改用。(请注意,在 Python 3.6 字典之前是无序的,因此“第一个”元素是任意元素。从 3.6 开始,它将基于插入顺序。如果您需要在旧版本中使用该行为或具有跨版本兼容性,则可以使用collections.OrderedDict) .

This works quite simply: we take the iterable from the dictionary view with iter(), then use next()to advance it by one and get the first key.

这很简单:我们从字典视图中使用 获取可迭代对象iter(),然后使用next()将它推进一个并获得第一个键。

If you need to iterate over the keys—then there is definitely no need to construct a list:

如果你需要遍历键——那么绝对没有必要构造一个列表:

for key in dict:
    ...

These are all advantageous when compared to using list()as it means a list isn't constructed - making it faster and more memory efficient (hence why the default behaviour of keys()was changed in 3.x). Even in Python 2.x you would be better off doing next(iter(dict.iterkeys()).

与 using 相比,这些都是有利的,list()因为这意味着未构造列表 - 使其更快且内存效率更高(因此为什么keys()在 3.x 中更改了默认行为)。即使在 Python 2.x 中,您也最好将next(iter(dict.iterkeys()).

Note all these things apply to dict.values()and dict.items()as well.

请注意,所有这些事情都适用于dict.values()并且dict.items()也适用。

回答by Tim Pozza

I've had success turning the iterables taken from a dictionary into a list. So, for dic.keys(), dic.values(), and dic.items(), in Python3.6, you can:

我已经成功地将字典中的可迭代对象转换为列表。因此,对于 dic.keys()、dic.values() 和 dic.items(),在 Python3.6 中,您可以:

dic = {'a':3, 'b':2, 'c':3}
print(dic)

dictkeys = dic.keys() # or values/items
print(dictkeys)

keylist = []
keylist.extend(iter(dictkeys)) # my big revelation
print('keylist', keylist)