📜  Python字典

📅  最后修改于: 2022-05-13 01:55:07.873000             🧑  作者: Mango

Python字典

Python中的Dictionary是数据值的无序集合,用于像 map 一样存储数据值,与仅包含单个值作为元素的其他数据类型不同,Dictionary 包含key:value对。字典中提供了键值,使其更加优化。

注意 –字典中的键不允许多态。

创建字典

在Python中,可以通过在花括号{}中放置一系列元素来创建字典,并用“逗号”分隔。 Dictionary 包含成对的值,一个是 Key,另一个对应的 pair 元素是它的Key:value 。字典中的值可以是任何数据类型并且可以重复,而键不能重复并且必须是不可变的。

注意 –字典键区分大小写,相同名称但不同大小写的 Key 将被区别对待。

Python3
# 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)


Python3
# 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)


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


Python3
# 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)


Python3
# 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])


Python3
# 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))


Python3
# 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'])


Python3
# 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)


Python3
# 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))


Python3
# 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))


Python3
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
 
 
# Deleting entire Dictionary
Dict.clear()
print("\nDeleting Entire Dictionary: ")
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() 创建。只需放置大括号{}即可创建空字典。

Python3

# 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'}

嵌套字典:

Python3

# 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 Dictionary 中,可以通过多种方式添加元素。通过定义值和键,一次可以将一个值添加到字典中,例如 Dict[Key] = 'Value'。可以使用内置的update()方法更新 Dictionary 中的现有值。嵌套键值也可以添加到现有字典中。

注意-在添加值时,如果键值已经存在,则更新该值,否则将带有该值的新键添加到字典中。

Python3

# 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)}

访问字典中的元素

为了访问字典的项目,请参考它的键名。键可以在方括号内使用。

Python3

# 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()的方法也有助于从字典中访问元素。

Python3

# 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

访问嵌套字典的元素

为了访问嵌套字典中任何键的值,请使用索引 [] 语法。

Python3

# 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将删除整个字典,因此在删除后打印它会引发错误。

Python3

# 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() 方法用于返回和删除指定键的值。

Python3

# 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() 从字典中返回并删除任意元素(键,值)对。

Python3

# 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()方法可以一次删除字典中的所有项目。

Python3

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

输出:

Deleting Entire Dictionary: 
{}

字典方法

MethodsDescription
copy()They copy() method returns a shallow copy of the dictionary.
clear()The clear() method removes all items from the dictionary.
pop()Removes and returns an element from a dictionary having the given key.
popitem()Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get()It is a conventional method to access a value for a key.
dictionary_name.values()returns a list of all the values available in a given dictionary.
str()Produces a printable string representation of a dictionary.
update()Adds dictionary dict2’s key-values pairs to dict
setdefault()Set dict[key]=default if key is not already in dict
keys()Returns list of dictionary dict’s keys
items()Returns a list of dict’s (key, value) tuple pairs
has_key()Returns true if key in dictionary dict, false otherwise
fromkeys()Create a new dictionary with keys from seq and values set to value.
type()Returns the type of the passed variable.
cmp()Compares elements of both dict.

最近关于Python字典的文章

https://youtu.be/z7z_e5

字典程序

  • 字典方法 – 第 1 组,第 2 组
  • 字典的 Get() 方法
  • 处理字典的缺失键
  • 有序字典
  • 订单字典()
  • 链图
  • 多数元素
  • Python中的字典和计数器找到选举的获胜者
  • 如何用 Python3 实现字典
  • 在Python中使用给定字符的可能单词
  • Python字典,设置和计数器来检查频率是否可以变得相同
  • Python字典交集
  • Python中的 OrderedDict()
  • 检查两个数字的二进制表示是否是字谜
  • Python Counter 查找最大字谜词子集的大小
  • 使用 List 和 Dictionary 在Python中一起打印字谜
  • 将元组列表转换为字典
  • 查找字符串中的所有重复字符
  • 从给定的句子中删除所有重复的单词
  • Python字典在字符串中查找镜像字符
  • Python计数器和字典交集示例(使用删除和重新排列创建字符串)
  • Python中序列中重复次数第二多的单词
  • Python字典理解
  • Python中第K个非重复字符使用列表理解和OrderedDict
  • 使用Python在字典中抓取和查找有序单词
  • Python中按值对字典列表进行排序的方法——使用itemgetter
  • 合并两个字典

有用的链接

  • 最近关于Python字典的文章
  • Python程序的输出——字典
  • Python程序的输出——字典
  • 编码实践平台
  • 多项选择题 - Python
  • Python分类中的所有文章