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

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

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

Python字典基础已经在下面的文章中讨论过

字典

本文讨论了一些字典方法。

1. str(dic) :- 此方法用于返回字符串,表示所有字典键及其值。

2. items() :- 此方法用于返回包含所有字典键和值的列表

# Python code to demonstrate working of
# str() and items()
  
# Initializing dictionary
dic = { 'Name' : 'Nandini', 'Age' : 19 }
  
# using str() to display dic as string
print ("The constituents of dictionary as string are : ")
print (str(dic))
  
# using str() to display dic as list
print ("The constituents of dictionary as list are : ")
print (dic.items())

输出:

The constituents of dictionary as string are : 
{'Name': 'Nandini', 'Age': 19}
The constituents of dictionary as list are : 
dict_items([('Name', 'Nandini'), ('Age', 19)])

3. len() :- 它返回字典元素的关键实体的计数

4. type() :- 该函数返回参数的数据类型

# Python code to demonstrate working of
# len() and type()
  
# Initializing dictionary
dic = { 'Name' : 'Nandini', 'Age' : 19, 'ID' : 2541997 }
  
# Initializing list
li = [ 1, 3, 5, 6 ]
  
# using len() to display dic size
print ("The size of dic is : ",end="")
print (len(dic))
  
# using type() to display data type
print ("The data type of dic is : ",end="")
print (type(dic))
  
# using type() to display data type
print ("The data type of li is : ",end="")
print (type(li))

输出:

The size of dic is : 3
The data type of dic is : 
The data type of li is : 

5. copy() :- 此函数将字典的浅表副本创建到其他字典中。

6. clear() :- 该函数用于清除字典内容。

# Python code to demonstrate working of
# clear() and copy()
  
# Initializing dictionary
dic1 = { 'Name' : 'Nandini', 'Age' : 19 }
  
# Initializing dictionary 
dic3 = {}
  
# using copy() to make shallow copy of dictionary
dic3 = dic1.copy()
  
# printing new dictionary
print ("The new copied dictionary is : ")
print (dic3.items())
  
# clearing the dictionary
dic1.clear()
  
# printing cleared dictionary
print ("The contents of deleted dictionary is : ",end="")
print (dic1.items())

输出:

The new copied dictionary is : 
dict_items([('Age', 19), ('Name', 'Nandini')])
The contents of deleted dictionary is : dict_items([])