Python字典用于以键值对格式存储数据。字典是Python中的数据类型,它可以模拟现实生活中的数据排列,其中某些特定键存在某些特定值。它是可变的数据结构。字典被定义为元素键和值。
换句话说,字典是键-值(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()方法还用于更新现有值。
注意:如果键值已经存在于字典中,则该值将被更新。否则,新关键字将添加到词典中。
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-dictionary.html
来源:LearnFk无涯教程网
示例-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()方法将键作为参数并删除关联的值。考虑以下示例。
# 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.在字典中,不能为相同的键存储多个值。如果为单个键传递多个值,那么最后分配的值将被视为键的值。
考虑以下示例。
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) | 它将字典转换为可打印的字符串表示形式。 |
4 | type(variable) | 它用于打印所传递变量的类型。 |
内置的python字典方法及其说明如下。
SN | 方法 | 说明 |
---|---|---|
1 | dic.clear() | 它用于删除字典中的所有项目。 |
2 | dict.copy() | 它返回字典的浅表副本。 |
3 | dict.fromkeys(iterable,value=None,/) | 从迭代器创建一个新字典,其值等于value。 |
4 | dict.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() | 它返回字典的所有值。 |
11 | len() | |
12 | popItem() | |
13 | pop() | |
14 | count() | |
15 | index() |
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)