dict2 = {'Name': 'sandeep', 'Age': 15, 'Class': '11th', 'school': 'GSBV'}
print(dict2)
if 'collage' in dict2.keys(): print(dict2['collage'])
else: print('no key found in dict')
print(dict2.setdefault('collage', 'this key do not exist in dict'))
if 'collage' in dict2.keys(): print(dict2['collage'])
else: print('no key found in dict')输出
no key found in dict
this key do not exist in dict
this key do not exist in dict它不打印
没有在dict中找到密钥
但相反,它打印了
此键在dict中不存在。
在最后一行中,为什么我的程序会有这种行为?
发布于 2022-08-26 23:04:51
setdefault正是它听起来的样子。它为字典中的键设置默认值。给该方法的第一个参数是要设置的key,第二个参数是默认值。因此,当您在已经有键值的setdefault上运行dict时,它就会忽略它。否则,它将将键设置为默认值。
例如:
>>> a = dict()
>>> a.setdefault('key', 'value')
'value'
>>> a.setdefault('key', 'othervalue')
'value'
>>> a
{'key': 'value'}如您所见,当dict为空时,调用setdefault添加了键、值对并返回值,但当再次调用时,它没有将value更改为othervalue,因为已经存在一个值。
这很方便,特别是在处理可迭代类型时。
例如:
>>> a = {}
>>> for char in ["A", "B", "C"]:
... for num in [1, 2, 3]:
... lst = a.setdefault(char, [])
... lst.append(num)
...
>>> a
{'A': [1, 2, 3], 'B': [1, 2, 3], 'C': [1, 2, 3]}如果没有setdefault,就需要编写一个条件语句,如果键已经设置或没有设置,则需要在每次迭代中进行检查。
https://stackoverflow.com/questions/73504931
复制相似问题