在Python中,字典是一种无序的数据项序列,可以用来记录数据项,就像地图一样。与其他只包含一个对象的替代数据结构不同,字典包含键值对。字典包含一个键-值字段,以提高这种数据类型的效率。

创建字典

我们可以通过将一组对象括在花括号中并用逗号隔开来创建Python中的字典。字典跟踪一对条目,其中一部分称为键,另一部分称为键的值,称为键值对。我们可以将任何数据类型存储为键的值,并为两个键分配相同的值,但键应为不可变且唯一的。

示例代码

# Initializing a dictionary with some elements   
Dictionary = {1: 'javatiku', 2: 'Python', 3: 'Dictionary'}  
print("\nDictionary created using curly braces: ")  
print(Dictionary)  
# Creating a Dictionary with keys of different data types  
Dictionary = {'Website': 'javatiku', 3: [2, 3, 5, 'Dictionary']}  
print("\nDictionary with keys of multiple data type: ")  
print(Dictionary)  

输出:

Dictionary created using curly braces: 
{1: 'javatiku', 2: 'Python', 3: 'Dictionary'}

Dictionary with keys of multiple data type: 
{'Website': 'javatiku', 3: [2, 3, 5, 'Dictionary']}

还可以使用内置的 dict() 方法生成字典。通过简单地放置两个大括号 {},可以创建一个空字典。

示例代码

# Initializing an empty Dictionary  
Dictionary = {}  
print("An empty Dictionary: ")  
print(Dictionary)  
   
# Creating a Dictionary using in-built dict() method  
Dictionary = dict({1: 'Python', 2: 'javatiku', 3:'Dictionary'})  
print("\nDictionary created by using dict() method: ")  
print(Dictionary)  
   
# Creating dictionary by key:value pair format  
Dictionary = dict([(1, 'javatiku'), (2, 'Python'), (3, 'Dictionary')])  
print("\nDictionary with key:value pair format: ")  
print(Dictionary)  

输出:

An empty Dictionary: 
{}

Dictionary created by using dict() method: 
{1: 'Python', 2: 'javatiku', 3: 'Dictionary'}

Dictionary with key:value pair format: 
{1: 'javatiku', 2: 'Python', 3: 'Dictionary'}

向字典中添加元素

可以使用多种方法将项目插入Python字典中。可以使用以下格式 Dictionary[Key] = 'Value' 向字典中添加项目。我们可以使用内置的 update() 函数来更新字典中的当前键。还可以将嵌套的键值对插入到现有的字典中。如果字典中存在键值对组合,将修改该键的值;如果不是这种情况,则创建一个新键,并将其添加到具有给定值的字典中。

示例代码

# Initializing an empty Dictionary  
Dictionary = {}  
print("The empty Dictionary: ")  
print(Dictionary)  
   
# Inserting key:value pairs one at a time  
Dictionary[0] = 'javatiku'  
Dictionary[2] = 'Python'  
Dictionary.update({ 3 : 'Dictionary'})  
print("\nDictionary after addition of these elements: ")  
print(Dictionary)  
   
# Adding a list of values to a single key  
Dictionary['list_values'] = 3, 4, 6  
print("\nDictionary after addition of the list: ")  
print(Dictionary)  
   
# Updating values of an already existing Key  
Dictionary[2] = 'Tutorial'  
print("\nUpdated dictionary: ")  
print(Dict)  
   
# Adding a nested Key to our dictionary  
Dictionary[5] = {'Nested_key' :{1 : 'Nested', 2 : 'Key'}}  
print("\nAfter addtion of a Nested Key: ")  
print(Dictionary)  

输出:

The empty Dictionary: 
{}

Dictionary after addition of these elements: 
{0: 'javatiku', 2: 'Python', 3: 'Dictionary'}

Dictionary after addition of the list: 
{0: 'javatiku', 2: 'Python', 3: 'Dictionary', 'list_values': (3, 4, 6)}

Updated dictionary: 
{1: 'javatiku', 2: 'Python'}

After addtion of a Nested Key: 
{0: 'javatiku', 2: 'Tutorial', 3: 'Dictionary', 'list_values': (3, 4, 6), 5: {'Nested_key': {1: 'Nested', 2: 'Key'}}}

从字典中删除元素

可以使用 pop() 函数从字典中删除特定的项。该函数返回删除的键的值。

popitem() 函数删除并返回给定字典中的任何(键,值)元素对。可以使用 clear() 函数一次删除所有对象。

还可以使用 del 关键字删除单个项目或整个字典。

示例代码

# Program to show how to remove elements from a dictionary  
  
# initializing a dictionary  
Dictionary = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}  
  
# removing a key:value pair from the dictionary using pop()  
Dictionary.pop(4)  
print("\nAfter removing a key using pop(): ")  
print(Dictionary)  
  
# remove any item at random using popitem()  
Dictionary.popitem()  
print("\nAfter removing an arbitrary key: ")  
print(Dictionary)  
  
# remove all the items present in dictionary  
print("\nAfter removing all the items: ")  
Dictionary.clear()  
print(Dictionary)  
  
# deleting the dictionary variable  
del Dictionary  
  
# Printing dictionary after deleting it  
try:  
    print(Dictionary)  
except:  
    print('No dictionary of the given name')  

输出:

After removing a key using pop(): 
{1: 'a', 2: 'b', 3: 'c', 5: 'e'}

After removing an arbitrary key: 
{1: 'a', 2: 'b', 3: 'c'}

After removing all the items: 
{}
No dictionary of the given name

Python字典方法

下面列出了可以与字典一起使用的方法。其中一些已经在本教程中提到。

方法描述
clear()删除字典中的所有项。
copy()返回字典的浅复制。
fromkeys(seq[, v])该函数使用seq的键和v的值(键的默认值为None)生成一个新的字典。
get(key[,d])该函数返回特定键的值。如果键不存在,则返回d。
items()返回以(键,值)格式包含字典内容的新对象。
keys()创建一个具有字典键的新对象。
pop(key[,d])删除与给定键相关联的项目并返回其值,或者如果未找到键,则返回d。如果未指定d并且在字典中找不到给定键,则引发KeyError。
popitem()删除并替换随机对象(键,值)。如果给定字典为空,则引发KeyError。
setdefault(key[,d])如果在字典中找到键,则返回关联的值。如果没有,则返回d并将键添加到d的值。
update([other])用给定字典覆盖现有键。
values()使用字典的元素初始化一个新的字典对象。

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