在Python中,字典是一种有用的数据结构,用于存储数据,因为它们能够模拟现实世界中的数据排列,其中特定键对应于给定的值。

数据以键值对的形式存储在Python字典中。

  • 这种数据结构是可变的。
  • 字典的组成部分由键和值组成。
  • 键必须只有一个组成部分。
  • 值可以是任何类型,包括整数、列表和元组。

换句话说,字典是一组键值对,其中值可以是任何Python对象。相反,键是不可变的Python对象,例如字符串、元组或数字。字典条目在Python版本3.7中是有序的。在Python 3.6及之前的版本中,字典通常是无序的。

创建字典

大括号是生成Python字典的最简单方式,尽管还有其他方法。通过在大括号中包围许多键值对,并使用冒号将每个键与其值分隔,可以构建字典。(:)。以下提供了定义字典的语法。

语法:

Dict = {"Name": "Gayle", "Age": 25}   

代码

Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}        
print(type(Employee))        
print("printing Employee data .... ")        
print(Employee)         

输出

<class 'dict'>
printing Employee data .... 
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}

Python提供了内置的dict()函数,也可用于创建字典。

用空的大括号{}可以创建空字典。

代码

# Creating an empty Dictionary       
Dict = {}       
print("Empty Dictionary: ")       
print(Dict)       
      
# Creating a Dictionary       
# with dict() method       
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})       
print("\nCreate Dictionary by using  dict(): ")       
print(Dict)       
      
# Creating a Dictionary       
# with each item as a Pair       
Dict = dict([(4, 'Rinku'), (2, Singh)])       
print("\nDictionary with each item as a pair: ")       
print(Dict)       

输出

Empty Dictionary: 
{}

Create Dictionary by using  dict(): 
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

Dictionary with each item as a pair: 
{4: 'Rinku', 2: 'Singh'}

访问字典值

要访问包含在列表和元组中的数据,我们已经学过索引。字典的键可以用来获取值,因为它们彼此之间是唯一的。下面的方法可以用来访问字典的值。

代码

Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}      
print(type(Employee))      
print("printing Employee data .... ")      
print("Name : %s" %Employee["Name"])      
print("Age : %d" %Employee["Age"])      
print("Salary : %d" %Employee["salary"])      
print("Company : %s" %Employee["Company"])       

输出

ee["Company"])    
Output
<class 'dict'>
printing Employee data .... 
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO

Python还提供了使用get()方法访问字典值的替代方法。这将得到与索引给出的相同结果。

添加字典值

字典是一种可变的数据类型,使用正确的键可以更改其值。Dict[key] = value 和 value 都可以修改。现有的值也可以使用update()方法来更新。

注意:如果键值对已经存在于字典中,则更新值。否则,字典中会添加新的键。

让我们看一个更新字典值的示例。

示例 - 1:

代码

# Creating an empty Dictionary       
Dict = {}       
print("Empty Dictionary: ")       
print(Dict)       
        
# Adding elements to dictionary one at a time       
Dict[0] = 'Peter'      
Dict[2] = 'Joseph'      
Dict[3] = 'Ricky'      
print("\nDictionary after adding 3 elements: ")       
print(Dict)       
        
# Adding set of values        
# with a single Key       
# The Emp_ages doesn't exist to dictionary      
Dict['Emp_ages'] = 20, 33, 24      
print("\nDictionary after adding 3 elements: ")       
print(Dict)       
  
# Updating existing Key's Value       
Dict[3] = 'JavaTpoint'      
print("\nUpdated key value: ")       
print(Dict)            

输出

Empty Dictionary: 
{}

Dictionary after adding 3 elements: 
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements: 
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value: 
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

示例 - 2:

代码

Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}         
print(type(Employee))        
print("printing Employee data .... ")        
print(Employee)        
print("Enter the details of the new employee....");        
Employee["Name"] = input("Name: ");        
Employee["Age"] = int(input("Age: "));        
Employee["salary"] = int(input("Salary: "));        
Employee["Company"] = input("Company:");        
print("printing the new data");        
print(Employee)     

输出

<class 'dict'>
printing Employee data .... 
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter the details of the new employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}

使用del关键字删除元素

可以使用del关键字删除字典的元素。以下是删除字典项的代码。

代码

Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}         
print(type(Employee))        
print("printing Employee data .... ")        
print(Employee)        
print("Deleting some of the employee data")         
del Employee["Name"]        
del Employee["Company"]        
print("printing the modified information ")        
print(Employee)        
print("Deleting the dictionary: Employee");        
del Employee        
print("Lets try to print it again ");        
print(Employee)       

输出

<class 'dict'>
printing Employee data .... 
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information 
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again 
NameError: name 'Employee' is not defined.

上面代码中的最后一个打印语句引发了错误,因为我们试图打印已删除的Employee字典。

使用pop()方法删除元素

在Python中,字典是一组键值对。您可以使用这种无序、可变的数据类型来检索、插入和删除项目,只需使用其键。pop()方法是从字典中删除元素的方法之一。在本文中,我们将讨论如何使用pop()方法从Python字典中删除项目。

使用pop()方法,可以删除与特定键相关联的值,然后返回该值。需要的唯一参数是要删除的元素的键。pop()方法可以按以下方式使用:

代码

# Creating a Dictionary       
Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}       
# Deleting a key        
# using pop() method       
pop_key = Dict1.pop(2)       
print(Dict1)  

输出

{1: 'JavaTpoint', 3: 'Website'}

此外,Python还提供了用于删除字典项的内置函数popitem()和clear()。与clear()方法不同,clear()方法从整个字典中删除所有元素,而popitem()方法从字典中删除任何元素。

迭代字典

可以使用for循环迭代字典,如下所示。

示例1

代码

# for loop to print all the keys of a dictionary    
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}        
for x in Employee:        
    print(x)   

输出

Name
Age
salary
Company

示例2

代码

#for loop to print all the values of the dictionary    
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"} for x in Employee:        
 print(Employee[x])       

输出

John
29
25000
WIPRO

示例3

代码

#for loop to print the values of the dictionary by using values() method.    
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}        
for x in Employee.values():        
    print(x)       

输出

John
29
25000
WIPRO

示例4

代码

#for loop to print the items of the dictionary by using items() method    
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}       
for x in Employee.items():        
    print(x)     

输出

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')

字典键的属性

  1. 在字典中,我们不能为相同的键存储多个值。如果为单个键传递多个值,那么最后分配的值将被视为键的值。

考虑以下示例。

代码

Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":    
"John"}        
for x,y in Employee.items():        
        print(x,y)           

输出

Name John
Age 29
Salary 25000
Company WIPRO
  1. 键不能属于Python中的任何可变对象。数字、字符串或元组可以用作键,但不可变对象如列表不能用作字典中的键。

考虑以下示例。

代码

Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"}        
for x,y in Employee.items():        
    print(x,y)         

输出

Traceback (most recent call last):
  File "dictionary.py", line 1, in 
    Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

内置的字典函数

函数是可以在构造上使用的方法,用于产生一个值。此外,构造不会改变。Python的一些方法可以与Python字典结合使用。

内置的Python字典方法如下所示,附带简要说明。

  • len()

通过len()函数在Python中返回字典的长度。每个键值对的字符串都会增加一个。

代码

dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}  
len(dict)  

输出

4
  • any()

与其在列表和元组中的操作方式一样,any()方法返回True,如果一个字典键确实具有求值为True的布尔表达式。

代码

dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}  
any({'':'','':'','3':''})  

输出

True
  • all()

与any()方法不同,all()方法只有在字典的每个键都包含True布尔值时才返回True。

代码

dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}  
all({1:'',2:'','':''})  

输出

False
  • sorted()

与它在列表和元组中的操作方式一样,sorted()方法返回字典的键的有序系列。升序排序不会影响原始的Python字典。

代码

dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}  
sorted(dict)  

输出

[ 1, 5, 7, 8]

内置的字典方法

以下是内置Python字典方法,以及简要说明和代码。

  • clear()

主要用于删除字典的所有项。

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# clear() method    
dict.clear()    
print(dict)    

输出

{ }
  • copy()

它返回一个创建的字典的浅层副本。

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# copy() method    
dict_demo = dict.copy()    
print(dict_demo)    

输出

{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
  • pop()

主要通过指定的键删除元素。

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# pop() method    
dict_demo = dict.copy()    
x = dict_demo.pop(1)    
print(x)    

输出

{2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
  • popitem()

删除最近输入的键值对

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# popitem() method    
dict_demo.popitem()    
print(dict_demo)    

输出

{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
  • keys()

返回字典的所有键。

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# keys() method    
print(dict_demo.keys())    

输出

dict_keys([1, 2, 3, 4, 5])
  • items()

返回所有键值对作为元组。

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# items() method    
print(dict_demo.items())   

输出

dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
  • get()

用于获取传递的键的值。

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# get() method    
print(dict_demo.get(3))   

输出

Facebook
  • update()

主要通过将dict2的键值对添加到此字典来更新整个字典。

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# update() method    
dict_demo.update({3: "TCS"})    
print(dict_demo)    

输出

{1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}
  • values()

返回字典的所有值。

代码

# dictionary methods    
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
# values() method    
print(dict_demo.values())    

输出

dict_values(['Hcl', 'WIPRO', 'TCS'])

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程