Python中的Dictionary方法| Set 2(update()、has_key()、fromkeys()…)

下面的集合1讨论了一些字典方法

null

Python中的Dictionary方法| Set 1(cmp()、len()、items()…)

本文将讨论更多的方法。

1.fromkeys(序号,值) :-此方法用于声明 新的序列字典 在其论点中提到。此功能还可以 用“value”参数初始化声明的字典 .

2.更新(dic) :-此函数用于 更新字典以添加其他字典键 .

# Python code to demonstrate working of
# fromkeys() and update()
# Initializing dictionary 1
dic1 = { 'Name' : 'Nandini' , 'Age' : 19 }
# Initializing dictionary 2
dic2 = { 'ID' : 2541997 }
# Initializing sequence
sequ = ( 'Name' , 'Age' , 'ID' )
# using update to add dic2 values in dic 1
dic1.update(dic2)
# printing updated dictionary values
print ( "The updated dictionary is : " )
print ( str (dic1))
# using fromkeys() to transform sequence into dictionary
dict = dict .fromkeys(sequ, 5 )
# printing new dictionary values
print ( "The new dictionary values are : " )
print ( str ( dict ))


输出:

The updated dictionary is : 
{'Age': 19, 'Name': 'Nandini', 'ID': 2541997}
The new dictionary values are : 
{'Age': 5, 'Name': 5, 'ID': 5}

3.有_key() :-如果 指定的密钥存在 在字典中,else返回false。

4.获取(密钥、定义值) :-此函数返回 与密钥关联的密钥值 在辩论中提到。如果密钥不存在,则返回默认值。

# Python code to demonstrate working of
# has_key() and get()
# Initializing dictionary
dict = { 'Name' : 'Nandini' , 'Age' : 19 }
# using has_key() to check if dic1 has a key
if dict .has_key( 'Name' ):
print ( "Name is a key" )
else : print ( "Name is not a key" )
# using get() to print a key value
print ( "The value associated with ID is : " )
print ( dict .get( 'ID' , "Not Present" ))
# printing dictionary values
print ( "The dictionary values are : " )
print ( str ( dict ))


输出:

Name is a key
The value associated with ID is : 
Not Present
The dictionary values are : 
{'Name': 'Nandini', 'Age': 19}

5.设置默认值(键、定义值) :-这个功能也 搜索钥匙 并像get()一样显示其值,但是 创建具有def_值的新密钥 如果钥匙不存在。

# Python code to demonstrate working of
# setdefault()
# Initializing dictionary
dict = { 'Name' : 'Nandini' , 'Age' : 19 }
# using setdefault() to print a key value
print ( "The value associated with Age is : " ,end = "")
print ( dict .setdefault( 'ID' , "No ID" ))
# printing dictionary values
print ( "The dictionary values are : " )
print ( str ( dict ))


输出:

The value associated with Age is : No ID
The dictionary values are : 
{'Name': 'Nandini', 'Age': 19, 'ID': 'No ID'}

本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享