Moh*_*ati 2683 python dictionary
我想在更新密钥的值之前测试字典中是否存在密钥.我写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
Run Code Online (Sandbox Code Playgroud)
我认为这不是完成这项任务的最佳方式.有没有更好的方法来测试字典中的密钥?
Chr*_* B. 2980
in是测试a中密钥是否存在的预期方法dict.
d = dict()
for i in range(100):
key = i % 10
if key in d:
d[key] += 1
else:
d[key] = 1
Run Code Online (Sandbox Code Playgroud)
如果您想要默认值,您可以随时使用dict.get():
d = dict()
for i in range(100):
key = i % 10
d[key] = d.get(key, 0) + 1
Run Code Online (Sandbox Code Playgroud)
...如果您想始终确保可以defaultdict从collections模块中使用的任何键的默认值,如下所示:
from collections import defaultdict
d = defaultdict(int)
for i in range(100):
d[i % 10] += 1
Run Code Online (Sandbox Code Playgroud)
...但一般来说,in关键字是最好的方法.
Jas*_*ker 1479
您无需拨打密钥:
if 'key1' in dict:
print "blah"
else:
print "boo"
Run Code Online (Sandbox Code Playgroud)
这会更快,因为它使用字典的散列而不是进行线性搜索,调用键就可以.
Mic*_*yan 263
您可以使用in关键字测试字典中是否存在密钥:
d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False
Run Code Online (Sandbox Code Playgroud)
在变异之前检查字典中是否存在键的常见用法是默认初始化值(例如,如果您的值是列表,并且您希望确保存在可以追加的空列表插入键的第一个值时).在这种情况下,您可能会发现collections.defaultdict()感兴趣的类型.
在旧代码中,您还可以找到一些has_key()用于检查字典中键的存在的弃用方法(仅使用key_name in dict_name,而不是).
Gre*_*ill 95
你可以缩短这个:
if 'key1' in dict:
...
Run Code Online (Sandbox Code Playgroud)
然而,这充其量只是一种美容改善.为什么你认为这不是最好的方法?
Wto*_*wer 50
有关接受答案的建议方法(10米循环)的速度执行的其他信息:
'key' in mydict 经过时间1.07秒mydict.get('key') 经过时间1.84秒mydefaultdict['key'] 经过时间1.07秒因此使用in或defaultdict建议使用get.
Dav*_*ger 48
我建议改用这种setdefault方法.听起来它会做你想要的一切.
>>> d = {'foo':'bar'}
>>> q = d.setdefault('foo','baz') #Do not override the existing key
>>> print q #The value takes what was originally in the dictionary
bar
>>> print d
{'foo': 'bar'}
>>> r = d.setdefault('baz',18) #baz was never in the dictionary
>>> print r #Now r has the value supplied above
18
>>> print d #The dictionary's been updated
{'foo': 'bar', 'baz': 18}
Run Code Online (Sandbox Code Playgroud)
maf*_*nya 44
python中的字典有一个get('key',default)方法.所以你可以设置一个默认值,以防没有密钥.
values = {...}
myValue = values.get('Key', None)
Run Code Online (Sandbox Code Playgroud)
Hun*_*hur 30
如何使用EAFP(更容易请求宽恕而非许可):
try:
blah = dict["mykey"]
# key exists in dict
except KeyError:
# key doesn't exist in dict
Run Code Online (Sandbox Code Playgroud)
查看其他SO帖子:
Cha*_*too 25
使用三元运算符:
message = "blah" if 'key1' in dict else "booh"
print(message)
Run Code Online (Sandbox Code Playgroud)
Bis*_*hra 17
您可以获得结果的方式是:
哪个更好取决于3件事:
阅读更多:http://paltman.com/try-except-performance-in-python-a-simple-test/
使用try/block而不是'in'或'if':
try:
my_dict_of_items[key_i_want_to_check]
except KeyError:
# Do the operation you wanted to do for "key not present in dict".
else:
# Do the operation you wanted to do with "key present in dict."
Run Code Online (Sandbox Code Playgroud)
小智 16
您可以使用has_key()方法:
if dict.has_key('xyz')==1:
#update the value for the key
else:
pass
Run Code Online (Sandbox Code Playgroud)
或者in如果找不到则设置默认值的方法:
if dict.has_key('xyz')==1:
#update the value for the key
else:
pass
Run Code Online (Sandbox Code Playgroud)
Mau*_*les 15
只是一个FYI加入克里斯.B(最佳答案):
d = defaultdict(int)
Run Code Online (Sandbox Code Playgroud)
也适用; 原因是调用int()返回0是defaultdict幕后的(当构造字典时),因此文档中的名称为"Factory Function".
Python字典有调用的方法__contains__.如果字典具有键,则此方法将返回True,否则返回False.
>>> temp = {}
>>> help(temp.__contains__)
Help on built-in function __contains__:
__contains__(key, /) method of builtins.dict instance
True if D has a key k, else False.
Run Code Online (Sandbox Code Playgroud)
小智 6
分享另一种使用布尔运算符检查键是否存在的方法。
d = {'a': 1, 'b':2}
keys = 'abcd'
for k in keys:
x = (k in d and 'blah') or 'boo'
print(x)
Run Code Online (Sandbox Code Playgroud)
这返回
>>> blah
>>> blah
>>> boo
>>> boo
Run Code Online (Sandbox Code Playgroud)
解释
首先你应该知道在 Python 中,0, None, 或长度为零的对象计算为False. 其他一切都评估为True. 布尔运算从左到右计算,并返回非 True 或 False 的操作数。
让我们看一个例子:
>>> 'Some string' or 1/0
'Some string'
>>>
Run Code Online (Sandbox Code Playgroud)
由于'Some string'计算为True,其余部分or不会被计算,并且不会产生除以零错误。
但是如果我们切换顺序1/0首先被评估并引发异常:
>>> 1/0 or 'Some string'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
Run Code Online (Sandbox Code Playgroud)
我们可以将其用于模式来检查密钥是否存在。
(k in d and 'blah')
Run Code Online (Sandbox Code Playgroud)
和
if k in d:
'blah'
else:
False
Run Code Online (Sandbox Code Playgroud)
如果键存在,这已经返回正确的结果,但我们希望它在不存在时打印 'boo'。所以,我们把结果和or它'boo'
>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>>
Run Code Online (Sandbox Code Playgroud)
检查字典中是否已存在给定键
为了了解如何做到这一点,我们首先检查可以在字典上调用的方法。方法如下:
d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Run Code Online (Sandbox Code Playgroud)
Python Dictionary clear() Removes all Items
Python Dictionary copy() Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys() Creates dictionary from given sequence
Python Dictionary get() Returns Value of The Key
Python Dictionary items() Returns view of dictionary (key, value) pair
Python Dictionary keys() Returns View Object of All Keys
Python Dictionary pop() Removes and returns element having given key
Python Dictionary popitem() Returns & Removes Element From Dictionary
Python Dictionary setdefault() Inserts Key With a Value if Key is not Present
Python Dictionary update() Updates the Dictionary
Python Dictionary values() Returns view of all values in dictionary
Run Code Online (Sandbox Code Playgroud)
检查密钥是否已存在的残酷方法可能是get():
d.get("key")
Run Code Online (Sandbox Code Playgroud)
其他两种有趣的方法items()和keys()听起来工作量太大。因此,让我们检查一下get()是否适合我们。我们有我们的字典d:
d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Run Code Online (Sandbox Code Playgroud)
打印显示我们没有的密钥将返回None:
print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1
Run Code Online (Sandbox Code Playgroud)
如果密钥存在或不存在,我们可能会用它来获取信息。但是,如果我们使用单个命令创建字典,请考虑以下问题key:None:
d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None
Run Code Online (Sandbox Code Playgroud)
get()如果某些值可能是,导致该方法不可靠None。这个故事的结局应该更快乐。如果我们使用in比较器:
print('key' in d) #True
print('key2' in d) #False
Run Code Online (Sandbox Code Playgroud)
我们得到正确的结果。我们可以检查一下Python字节码:
import dis
dis.dis("'key' in d")
# 1 0 LOAD_CONST 0 ('key')
# 2 LOAD_NAME 0 (d)
# 4 COMPARE_OP 6 (in)
# 6 RETURN_VALUE
dis.dis("d.get('key2')")
# 1 0 LOAD_NAME 0 (d)
# 2 LOAD_METHOD 1 (get)
# 4 LOAD_CONST 0 ('key2')
# 6 CALL_METHOD 1
# 8 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)
这表明in比较运算符不仅比更加可靠,而且甚至更快get()。
| 归档时间: |
|
| 查看次数: |
3217588 次 |
| 最近记录: |