Python 中的字典是键值的集合,用于像映射一样存储数据值,与其他仅保存单个值作为元素的数据类型不同。
Python 中的字典示例
字典保存键:值对,字典中提供了Key-Value。
Dict = {1: 'Jkhxw', 2: 'For', 3: 'Geeks'}
print(Dict)
输出:
{1: 'Jkhxw', 2: 'For', 3: 'Geeks'}
创建字典
在Python中,可以通过将一系列元素放在大括号内(用“逗号”分隔)来创建字典。Dictionary 保存成对的值,一个是 Key,另一个对应的对元素是其Key:value。字典中的值可以是任何数据类型并且可以重复,而键不能重复并且必须是不可变的。
注意 –字典键区分大小写,名称相同但大小写不同的键将被区别对待。
# 使用整数键创建字典
Dict = {1: 'Jkhxw', 2: 'For', 3: 'Geeks'}
print("\n使用整数键创建的字典: ")
print(Dict)
# 使用混合键创建字典
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\n使用混合键创建的字典: ")
print(Dict)
输出:
使用整数键创建的字典:
{1: 'Jkhxw', 2: 'For', 3: 'Geeks'}
使用混合键创建的字典:
{'Name': 'Geeks', 1: [1, 2 , 3, 4]}
字典也可以通过内置函数 dict() 创建。只需放置大括号{}即可创建空字典。
# 创建一个空字典
Dict = {}
print("空字典: ")
print(Dict)
# 使用dict()方法创建字典
Dict = dict({1: 'Jkhxw', 2: 'For', 3: 'Geeks'})
print("\n使用dict()方法创建的字典: ")
print(Dict)
# 创建一个包含键值对的字典
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\n每个项都作为一对创建的字典: ")
print(Dict)
输出:
空字典:
{}
使用dict()方法创建的字典:
{1: 'Jkhxw', 2: 'For', 3: 'Geeks'}
每个项目都作为一对创建的字典:
{1: 'Geeks', 2: 'For'}
嵌套字典
Python 中的字典嵌套是指在一个字典内部包含另一个或多个字典作为其值。这样可以创建更复杂的数据结构,用于表示层次化的信息或更结构化的数据。
# 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'}}
将元素添加到字典中
可以通过多种方式添加元素。通过定义值和键,可以一次将一个值添加到字典中,例如 Dict[Key] = ‘Value’。可以使用内置的update()方法来更新字典中的现有值。嵌套键值也可以添加到现有字典中。
注意-添加值时,如果键值已存在,则该值会更新,否则带有该值的新键将添加到字典中。
# 创建一个空字典
Dict = {}
print("空字典: ")
print(Dict)
# 逐个添加元素
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\n添加3个元素后的字典: ")
print(Dict)
# 将一组值添加到单个键中
Dict['Value_set'] = 2, 3, 4
print("\n再添加3个元素后的字典: ")
print(Dict)
# 更新现有键的值
Dict[2] = 'Welcome'
print("\n更新后的键值: ")
print(Dict)
# 向字典添加嵌套键值对
Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}
print("\n添加嵌套键后的字典: ")
print(Dict)
输出:
空字典:
{}
添加3个元素后的字典:
{0: 'Geeks', 2: 'For', 3: 1}
再添加3个元素后的字典:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
更新后的键值:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
添加嵌套键后的字典:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}}
访问字典的元素
为了访问字典的项目,请参考其键名称。键可以在方括号内使用。
# Python program to demonstrate
# accessing a element from a Dictionary
# 创建一个字典
Dict = {1: 'Jkhxw', 'name': 'For', 3: 'Geeks'}
# 使用键访问元素
print("使用键访问元素:")
print(Dict['name'])
# 使用键访问元素
print("使用键访问元素:")
print(Dict[1])
输出:
使用键访问元素:
For
使用键访问元素:
Geeks
访问嵌套字典的元素
为了访问嵌套字典中任何键的值,请使用索引 [] 语法。
# 创建一个字典
Dict = {'Dict1': {1: 'Jkhxw'},
'Dict2': {'Name': 'For'}}
# 使用键访问元素
print(Dict['Dict1']) # 访问 'Dict1' 键对应的元素
print(Dict['Dict1'][1]) # 访问 'Dict1' 键对应的字典中的键 1 对应的元素
print(Dict['Dict2']['Name']) # 访问 'Dict2' 键对应的字典中的键 'Name' 对应的元素
输出:
{1: 'Jkhxw'}
Jkhxw
For
使用 del 关键字删除元素
可以使用 del 关键字删除字典中的项目,如下所示。
# Python程序演示
# 使用del关键字删除元素
# 创建一个字典
Dict = {1: 'Jkhxw', 'name': 'For', 3: 'Geeks'}
print("字典 =")
print(Dict)
# 删除一些字典数据
del(Dict[1])
print("删除数据后的字典=")
print(Dict)
输出:
字典 =
{1: 'Jkhxw', 'name': 'For', 3: 'Geeks'}
删除数据后的字典=
{'name': 'For', 3: 'Geeks'}
Python字典方法
方法 | 描述 |
---|---|
dic.clear() | 从字典中删除所有元素。 |
dict.copy() | 返回字典的副本。 |
dict.get(key, default) | 返回指定键的值,如果键不存在,则返回默认值。 |
dict.items() | 返回包含每个键值对的元组的列表。 |
dict.keys() | 返回包含字典的键的列表。 |
dict.update(dict2) | 使用指定的键值对更新字典。 |
dict.values() | 返回字典的所有值的列表。 |
pop(key) | 删除具有指定键的元素。 |
popitem() | 删除最后插入的键值对。 |
dict.setdefault(key, default) | 如果字典中不存在指定的键,则将其设置为默认值。 |
key in dict | 如果字典包含指定的键,返回True。 |
# 所有字典方法的演示
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
# copy() 方法
dict2 = dict1.copy()
print(dict2)
# clear() 方法
dict1.clear()
print(dict1)
# get() 方法
print(dict2.get(1))
# items() 方法
print(dict2.items())
# keys() 方法
print(dict2.keys())
# pop() 方法
dict2.pop(4)
print(dict2)
# popitem() 方法
dict2.popitem()
print(dict2)
# update() 方法
dict2.update({3: "Scala"})
print(dict2)
# values() 方法
print(dict2.values())
输出:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])