为什么要使用dict.keys? [英] Why use dict.keys?

查看:117
本文介绍了为什么要使用dict.keys?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近写了一些看起来像这样的代码:

I recently wrote some code that looked something like this:

# dct is a dictionary
if "key" in dct.keys():

但是,后来我发现我可以通过以下方式获得相同的结果:

However, I later found that I could achieve the same results with:

if "key" in dct:

这个发现让我开始思考,我开始进行一些测试,看看是否有一种情况,当我必须使用字典的keys方法时.但是我的结论是,没有.

This discovery got me thinking and I began to run some tests to see if there could be a scenario when I must use the keys method of a dictionary. My conclusion however is no, there is not.

如果我想要列表中的键,我可以这样做:

If I want the keys in a list, I can do:

keys_list = list(dct)

如果要遍历键,可以执行以下操作:

If I want to iterate over the keys, I can do:

for key in dct:
    ...

最后,如果我想测试键是否在dct中,可以像上面一样使用in.

Lastly, if I want to test if a key is in dct, I can use in as I did above.

总结起来,我的问题是:我错过了什么吗?可能存在我必须使用keys方法的情况吗?...还是仅仅是早期Python安装中的遗留方法应该被忽略?

Summed up, my question is: am I missing something? Could there ever be a scenario where I must use the keys method?...or is it simply a leftover method from an earlier installation of Python that should be ignored?

推荐答案

在Python 3上,使用dct.keys()获取

On Python 3, use dct.keys() to get a dictionary view object, which lets you do set operations on just the keys:

>>> for sharedkey in dct1.keys() & dct2.keys():  # intersection of two dictionaries
...     print(dct1[sharedkey], dct2[sharedkey])

在Python 2.7中,您将为此使用dct.viewkeys().

In Python 2.7, you'd use dct.viewkeys() for that.

在Python 2中,dct.keys()返回一个列表,即字典中键的副本.可以将其传递给一个单独的对象,该对象可以单独操作,包括在不影响字典本身的情况下删除元素;但是,您可以使用list(dct)创建相同的列表,该列表在Python 2和3中均可使用.

In Python 2, dct.keys() returns a list, a copy of the keys in the dictionary. This can be passed around an a separate object that can be manipulated in its own right, including removing elements without affecting the dictionary itself; however, you can create the same list with list(dct), which works in both Python 2 and 3.

您确实不希望其中任何一个用于迭代或成员资格测试;始终分别使用for key in dctkey in dct.

You indeed don't want any of these for iteration or membership testing; always use for key in dct and key in dct for those, respectively.

这篇关于为什么要使用dict.keys?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆