当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python dict setdefault()用法及代码示例


字典Python中的数据是一个无序的数据值集合,用于存储数据值(如Map),与其他仅将单个值作为元素的数据类型不同,Dictionary拥有 key:value对。

在Python字典中,setdefault()方法返回键的值(如果键在字典中)。如果不是,则将具有值的键插入字典。

用法: dict.setdefault(key[, default_value])

参数:它带有两个参数:
key -在字典中要搜索的键。
default_value(可选)-如果 key 不在词典中,则将值default_value的 key 插入到词典中。如果未提供,则default_value将为“无”。

返回:
key 的值(如果它在字典中)。
如果key不在词典中并且未指定default_value,则为None。
如果 key 不在词典中,并且指定了default_value,则为default_value。


范例1:

# Python program to show working 
# of setdefault() method in Dictionary 
  
# Dictionary with single item  
Dictionary1 = { 'A':'Geeks', 'B':'For', 'C':'Geeks'} 
  
# using setdefault() method 
Third_value = Dictionary1.setdefault('C') 
print("Dictionary:", Dictionary1) 
print("Third_value:", Third_value)

输出:

Dictionary:{'A':'Geeks', 'C':'Geeks', 'B':'For'}
Third_value:Geeks


范例2:当键不在词典中时。

# Python program to show working 
# of setdefault() method in Dictionary 
  
# Dictionary with single item  
Dictionary1 = { 'A':'Geeks', 'B':'For'} 
  
# using setdefault() method 
# when key is not in the Dictionary 
Third_value = Dictionary1.setdefault('C') 
print("Dictionary:", Dictionary1) 
print("Third_value:", Third_value) 
  
# using setdefault() method 
# when key is not in the Dictionary 
# but default value is provided 
Fourth_value = Dictionary1.setdefault('D', 'Geeks') 
print("Dictionary:", Dictionary1) 
print("Fourth_value:", Fourth_value)

输出:

Dictionary:{'A':'Geeks', 'B':'For', 'C':None}
Third_value:None
Dictionary:{'A':'Geeks', 'B':'For', 'C':None, 'D':'Geeks'}
Fourth_value:Geeks


相关用法


注:本文由纯净天空筛选整理自Akanksha_Rai大神的英文原创作品 Python Dictionary | setdefault() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。