📜  Python字典

📅  最后修改于: 2020-10-24 09:09:42             🧑  作者: Mango

Python字典

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

  • 键必须是一个元素
  • 值可以是任何类型,例如列表,元组,整数等。

换句话说,我们可以说字典是键-值对的集合,其中值可以是任何Python对象。相反,键是不可变的Python对象,即Numbers, 字符串或tuple。

创建字典

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

句法:

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

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

让我们看一个创建字典并print其内容的示例。

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

输出量


Printing Employee data .... 
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}

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

# Creating an empty Dictionary 
Dict = {} 
print("Empty Dictionary: ") 
print(Dict) 

# Creating a Dictionary 
# with dict() method 
Dict = dict({1: 'Java', 2: 'T', 3:'Point'}) 
print("\nCreate Dictionary by using  dict(): ") 
print(Dict) 

# Creating a Dictionary 
# with each item as a Pair 
Dict = dict([(1, 'Devansh'), (2, 'Sharma')]) 
print("\nDictionary with each item as a pair: ") 
print(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": "John", "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"])

输出:


printing Employee data .... 
Name : John
Age : 29
Salary : 25000
Company : GOOGLE

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

添加字典值

字典是可变数据类型,可以使用特定键来更新其值。该值可以与键Dict [key] = 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": "John", "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: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

使用del关键字删除元素

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

Employee = {"Name": "John", "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)  

输出:


printing Employee data .... 
{'Name': 'John', '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

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

  • 使用pop()方法

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

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

输出:

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

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

迭代字典

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

例子1

#for循环print字典的所有键

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

输出:

Name
Age
salary
Company

例子2

#for循环以print字典的所有值

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

输出:

John
29
25000
GOOGLE

示例-3

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

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

输出:

John
29
25000
GOOGLE

例子4

#for循环通过使用items()方法print字典中的项目。

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

输出:

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

字典键的属性

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

考虑以下示例。

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

输出:

Name John
Age 29
Salary 25000
Company GOOGLE

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

考虑以下示例。

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

内置词典功能

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

SN Function Description
1 cmp(dict1, dict2) It compares the items of both the dictionary and returns true if the first dictionary values are greater than the second dictionary, otherwise it returns false.
2 len(dict) It is used to calculate the length of the dictionary.
3 str(dict) It converts the dictionary into the printable string representation.
4 type(variable) It is used to print the type of the passed variable.

内置词典方法

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

SN Method Description
1 dic.clear() It is used to delete all the items of the dictionary.
2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable, value = None, /) Create a new dictionary from the iterable with the values equal to value.
4 dict.get(key, default = “None”) It is used to get the value specified for the passed key.
5 dict.has_key(key) It returns true if the dictionary contains the specified key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= “None”) It is used to set the key to the default value if the key is not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-value pair of dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
11 len()
12 popItem()
13 pop()
14 count()
15 index()