Python3 - Dic(字典)

Python3 - Dic(字典) 首页 / Python3入门教程 / Python3 - Dic(字典)

Python字典用于以键值对格式存储数据。字典是Python中的数据类型,它可以模拟现实生活中的数据排列,其中某些特定键存在某些特定值。它是可变的数据结构。字典被定义为元素键和值。

  • 键(key)必须是单个元素
  • 值(value)可以是列表,元组,整数等任何类型。

换句话说,字典是键-值(key-value)对的集合,其中值可以是任何Python对象。相反,键是不变的Python对象,即Numbers,字符串或元组。

创建字典

可以使用大括号{}括起来的多个键/值对来创建字典,每个键与其值之间用冒号(:)分隔。定义字典的语法如下。

Dict = {"Name": "Tom", "Age": 22}  

在上面的词典 Dict 中,键 Name Age 是作为不可变对象的字符串。

让无涯教程看一个创建字典并打印其内容的示例。

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
print(type(Employee))  
print("printing Employee data .... ")  
print(Employee)  

输出

<class 'dict'>
Printing Employee data .... 
{'Name': 'Learnfk', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}

Python提供了内置函数 dict()方法,该方法也可用于创建字典。空花括号{}用于创建空字典。

输出:

Empty Dictionary: 
{}

Create Dictionary by using dict(): 
{1: 'Java', 2: 'T', 3: 'Point'}

Dictionary with each item as a pair: 
{1: 'Devansh', 2: 'Sharma'}

访问元素

已经讨论了如何通过使用索引在列表和元组中访问数据。但是,可以使用键在字典中访问值,因为键在字典中是唯一的。

可以通过以下方式访问字典值。

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE"}
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"])

输出:

<class 'dict'>
printing Employee data .... 
Name : Learnfk
Age : 29
Salary : 25000
Company : GOOGLE

Python提供了一种使用get()方法访问字典值的替代方法。它会产生与索引相同的结果。

添加元素

字典是可变数据类型,可以使用特定键来更新其值。可以与键 Dict [key] = value 一起更新值。 update()方法还用于更新现有值。

注意:如果键值已经存在于字典中,则该值将被更新。否则,新关键字将添加到词典中。

示例-1:

# 创建一个空词典
Dict = {} 
print("Empty Dictionary: ") 
print(Dict) 
  
# 一次将元素添加到字典中
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ") 
print(Dict) 
  
# T他的emp_ages不存在于字典中
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ") 
print(Dict) 
  
# Updating existing Key's Value 
Dict[3] = 'Learnfk'
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: 'Learnfk', 'Emp_ages': (20, 33, 24)}

示例-2:

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
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)  

输出:

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: 'Learnfk', 'Emp_ages': (20, 33, 24)}

删除元素

可以使用 del 关键字删除字典中的各项,如下所示。

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
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': 'Learnfk', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information 
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again 
NameError: name 'Employee' is not defined

上面的代码中的最后一个打印语句,它引发了一个错误,因为无涯教程试图打印已经删除的Employee字典。

  • 使用pop()方法

pop()方法将键作为参数并删除关联的值。考虑以下示例。

# Creating a Dictionary 
Dict = {1: 'Learnfk', 2: 'Peter', 3: 'Thomas'} 
# Deleting a key  
# using pop() method 
pop_ele = Dict.pop(3) 
print(Dict)

输出:

{1: 'Learnfk', 2: 'Peter'}

Python还提供了内置popitem()和clear()方法,用于从字典中删除元素。 popitem()删除字典中的任意元素,而clear()方法删除整个字典中的所有元素。

迭代字典

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

#for循环以打印字典的所有键

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
for x in Employee:  
    print(x)

输出:

Name
Age
salary
Company

#for循环以打印字典的所有值

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
for x in Employee:  
    print(Employee[x])

输出:

Learnfk
29
25000
GOOGLE

#for循环以使用values()方法打印字典的值。

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
for x in Employee.values():  
    print(x)

输出:

Learnfk
29
25000
GOOGLE

#for循环以使用items()方法打印字典中的项目。

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
for x in Employee.items():  
    print(x)

输出:

('Name', 'Learnfk')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')

键的属性

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

链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-dictionary.html

来源:LearnFk无涯教程网

考虑以下示例。

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

输出:

Name Learnfk
Age 29
Salary 25000
Company GOOGLE

2.在python中,键不能是任何可变对象。可以使用数字,字符串或元组作为键,但是不能使用任何可变对象(例如列表)作为字典中的键。

Employee = {"Name": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE",[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": "Learnfk", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

内置函数

内置的python字典方法及其说明如下。

SN函数说明
1 cmp(dict1,dict2)它比较两个字典的项,如果第一个字典的值大于第二个字典的值,则返回true,否则返回false。
2 len(dict)它用于计算字典的长度。
3 str(dict)它将字典转换为可打印的字符串表示形式。
4type(variable)它用于打印所传递变量的类型。

内置方法

内置的python字典方法及其说明如下。

SN方法说明
1 dic.clear()它用于删除字典中的所有项目。
2dict.copy()
它返回字典的浅表副本。
3dict.fromkeys(iterable,value=None,/)
从迭代器创建一个新字典,其值等于value。
4dict.get(key,default =" None")
它用于获取为传递的键指定的值。
5 dict.has_key(key)如果字典中包含指定的键,则返回true。
6 dict.items()它将所有键值对作为元组返回。
7 dict.keys()它返回字典的所有键。
8 dict.setdefault(key,default =" None")如果未在字典中指定键,则用于将键设置为默认值
9 dict.update(dict2)它通过将dict2的键值对添加到此字典来更新字典。
10 dict.values()它返回字典的所有值。
11len()
12 popItem()
13 pop()
14count()
15index()

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

玩转Git三剑客 -〔苏玲〕

重学前端 -〔程劭非(winter)〕

Linux实战技能100讲 -〔尹会生〕

编辑训练营 -〔总编室〕

Kafka核心源码解读 -〔胡夕〕

Selenium自动化测试实战 -〔郭宏志〕

说透区块链 -〔自游〕

Redis源码剖析与实战 -〔蒋德钧〕

中间件核心技术与实战 -〔丁威〕

好记忆不如烂笔头。留下您的足迹吧 :)