专业编程基础技术教程

网站首页 > 基础教程 正文

Python字典(Dictionary)

ccvgpt 2024-11-23 11:58:11 基础教程 1 ℃

Python中的Dictionary是数据值的无序集合,用于存储数据值(如映射),与其他仅将单个值作为元素的数据类型不同,Dictionary拥有key:value对。字典中提供了键值以使其更优化。

创建字典

Python字典(Dictionary)

在Python中,可以通过将元素序列放在大括号中(用逗号分隔)来创建字典。Dictionary保存一对值,一个是Key,另一个对应的pair元素是它的Key:value。字典中的值可以是任何数据类型并且可以重复,而键不能重复并且必须是不可变的。

注意:字典键区分大小写,名称相同,但键的大小写会被区别对待。

# Creating a Dictionary  
# with Integer Keys 
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} 
print("\nDictionary with the use of Integer Keys: ") 
print(Dict) 
  
# Creating a Dictionary  
# with Mixed keys 
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} 
print("\nDictionary with the use of Mixed Keys: ") 
print(Dict) 

输出:

Dictionary with the use of Integer Keys: 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys: 
{1: [1, 2, 3, 4], 'Name': 'Geeks'}

字典也可以由内置函数dict()创建。只需放置到大括号{}即可创建空字典。

# Creating an empty Dictionary 
Dict = {} 
print("Empty Dictionary: ") 
print(Dict) 
  
# Creating a Dictionary 
# with dict() method 
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) 
print("\nDictionary with the use of dict(): ") 
print(Dict) 
  
# Creating a Dictionary 
# with each item as a Pair 
Dict = dict([(1, 'Geeks'), (2, 'For')]) 
print("\nDictionary with each item as a pair: ") 
print(Dict) 

输出:

Empty Dictionary: 
{}

Dictionary with the use of dict(): 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair: 
{1: 'Geeks', 2: 'For'}

嵌套字典

# Creating a Nested Dictionary  
# as shown in the below image 
Dict = {1: 'Geeks', 2: 'For',  
        3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}} 
  
print(Dict)  

输出:

{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

向字典添加元素

在Python字典中,可以通过多种方式添加元素。一次只能添加一个值到字典中,方法是定义值和键,例如Dict[key]=“value”。可以使用内置的update()方法更新字典中的现有值。嵌套的键值也可以添加到现有字典中。

注意:在添加值时,如果键值已经存在,则会更新该值,否则会向字典中添加具有该值的新键。

# Creating an empty Dictionary 
Dict = {} 
print("Empty Dictionary: ") 
print(Dict) 
  
# Adding elements one at a time 
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ") 
print(Dict) 
  
# Adding set of values  
# to a single Key 
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ") 
print(Dict) 
  
# Updating existing Key's Value 
Dict[2] = 'Welcome'
print("\nUpdated key value: ") 
print(Dict) 
  
# Adding Nested Key value to Dictionary 
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}} 
print("\nAdding a Nested Key: ") 
print(Dict) 

输出:

Empty Dictionary: 
{}

Dictionary after adding 3 elements: 
{0: 'Geeks', 2: 'For', 3: 1}

Dictionary after adding 3 elements: 
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value: 
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key: 
{0: 'Geeks', 2: 'Welcome', 3: 1, 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}, 'Value_set': (2, 3, 4)}

从字典访问元素

要访问字典的项,请参阅字典的键名。可以在方括号内使用键。

# Python program to demonstrate   
# accessing a element from a Dictionary  
  
# Creating a Dictionary  
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 
  
# accessing a element using key 
print("Accessing a element using key:") 
print(Dict['name']) 
  
# accessing a element using key 
print("Accessing a element using key:") 
print(Dict[1]) 

输出:

Accessing a element using key:
For

Accessing a element using key:
Geeks

还有一个名为get()的方法也有助于访问字典中的元素。

# Creating a Dictionary  
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 
  
# accessing a element using get() 
# method 
print("Accessing a element using get:") 
print(Dict.get(3)) 

输出:

Accessing a element using get:
Geeks

访问嵌套字典的元素

要访问嵌套字典中任何键的值,请使用index[]语法。

# Creating a Dictionary 
Dict = {'Dict1': {1: 'Geeks'}, 
        'Dict2': {'Name': 'For'}} 
  
# Accessing element using key 
print(Dict['Dict1']) 
print(Dict['Dict1'][1]) 
print(Dict['Dict2']['Name']) 

输出:

{1: 'Geeks'}
Geeks
For

从字典中删除元素

使用del关键字

在Python字典中,可以使用del关键字来删除键。使用del关键字,可以删除字典和整个字典中的特定值。嵌套字典中的项也可以通过使用del关键字并提供特定的嵌套键和要从该嵌套字典中删除的特定键来删除。

注意:del Dict将删除整个字典,因此在删除后打印它将导致错误。

# Initial Dictionary 
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks', 
        'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'}, 
        'B' : {1 : 'Geeks', 2 : 'Life'}} 
print("Initial Dictionary: ") 
print(Dict) 
  
# Deleting a Key value 
del Dict[6] 
print("\nDeleting a specific key: ") 
print(Dict) 
  
# Deleting a Key from 
# Nested Dictionary 
del Dict['A'][2] 
print("\nDeleting a key from Nested Dictionary: ") 
print(Dict) 

输出:

Initial Dictionary: 
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 6: 'To', 7: 'Geeks'}

Deleting a specific key: 
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}

Deleting a key from Nested Dictionary: 
{'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}

使用pop()方法

Pop()方法用于返回和删除指定键的值。

# Creating a Dictionary 
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 
  
# Deleting a key  
# using pop() method 
pop_ele = Dict.pop(1) 
print('\nDictionary after deletion: ' + str(Dict)) 
print('Value associated to poped key is: ' + str(pop_ele)) 

输出:

Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
Value associated to poped key is: Geeks

使用popitem()方法

popitem()返回并从字典中删除一个任意元素(键,值)对。

# Creating Dictionary 
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 
  
# Deleting an arbitrary key 
# using popitem() function 
pop_ele = Dict.popitem() 
print("\nDictionary after deletion: " + str(Dict)) 
print("The arbitrary pair returned is: " + str(pop_ele)) 

输出:

Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
The arbitrary pair returned is: (1, 'Geeks')

使用clear()方法

使用clear()方法可以一次删除字典中的所有项。

# Creating a Dictionary 
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 
  
  
# Deleting entire Dictionary 
Dict.clear() 
print("\nDeleting Entire Dictionary: ") 
print(Dict) 

输出:

Deleting Entire Dictionary: 
{}

词典方法

最近发表
标签列表