📜  Python中的字典方法|设置 2 (update(), has_key(), fromkeys()…)

📅  最后修改于: 2022-05-13 01:54:20.851000             🧑  作者: Mango

Python中的字典方法|设置 2 (update(), has_key(), fromkeys()…)

一些 Dictionary 方法在下面的集合 1 中讨论

Python中的字典方法|设置 1 (cmp(), len(), items()…)

本文讨论了更多方法。

1. fromkeys(seq,value) :- 此方法用于从其参数中提到的序列中声明一个新字典。此函数还可以使用“值”参数初始化声明的字典

2. update(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. has_key() :- 如果指定的键存在于字典中,此函数返回 true,否则返回 false。

4. get(key, def_val) :- 该函数返回与参数中提到的键关联的键值。如果 key 不存在,则返回默认值。

# 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. setdefault(key, def_value) :- 该函数还搜索一个键并显示其值,如 get() 但是,如果键不存在,它会使用 def_value 创建新键

# 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'}