赞
踩
目录
dict()函数在 Python 中用于创建一个新的字典对象。字典是一种无序的键值对集合,它允许我们根据键来存储和检索值。常见的应用场景有:
1、动态数据存储:字典非常适合存储动态数据,这些数据可能在运行时才会确定其键和值。例如,我们可以根据用户的输入或外部数据源动态地创建和更新字典。
2、配置文件和参数设置:许多程序需要配置文件来指定不同的设置或参数。字典可以用来存储这些配置项和它们的值,使得程序能够灵活地读取和修改配置。
3、统计数据:字典非常适合用来统计和记录数据,例如,统计文本中单词出现的频率。
4、映射和转换:字典可以用来实现键和值之间的映射关系,这在数据转换和替换时非常有用。
5、解析JSON数据:当从外部源(如API)接收JSON数据时,json.loads()函数通常会将JSON字符串解析为Python字典,从而方便后续处理。
6、缓存和状态管理:字典可以用作临时存储数据的缓存,或者在程序执行期间跟踪状态信息。
7、构建复杂数据结构:字典可以包含其他字典、列表或其他复杂数据类型,从而构建出嵌套的数据结构。
这些只是dict()函数的一些常见应用场景。实际上,由于字典的灵活性和便利性,它在 Python 编程中几乎无处不在,是构建复杂程序和数据结构的重要工具。
- # 1.函数:dict()
- # 2.功能:用于创建一个新的字典或根据传入的参数创建一个字典对象
- # 3.语法:
- # 3-1、dict(**kwarg)
- # 3-2、dict(mapping, **kwarg)
- # 3-3、dict(iterable, **kwarg)
- # 4.参数:
- # 4-1、`**kwarg`:一到多个关键字参数,这些关键字参数及其对应的值将被添加到字典中
- # 4-2、`mapping`:另一个字典,其键值对将被添加到新字典中,如zip()函数
- # 4-3、`iterable`:一个可迭代对象,其中包含可迭代的键值对(通常是包含两个元素的元组或其他可迭代对象)
- # 5.返回值:一个字典,如果不传入任何参数,则返回空字典
- # 6.说明:
- # 6-1、使用dict()函数通过给定的关键字参数创建字典时,name键名必须都是Python中的标识符,否则会提示SyntaxError错误,如下:
- # SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
- # print(dict(1='a',2='b'))
- # 7.示例:
- # 应用1:字典的增、删、改、查操作
- # 增(添加键值对)
- # 可以通过直接赋值的方式向字典中添加新的键值对:
- my_dict = {}
- my_dict['key1'] = 'value1' # 添加键值对 'key1': 'value1'
- # 删(删除键值对或字典)
- #可以使用 `del` 语句或 `pop()` 方法来删除字典中的键值对,也可以使用 `clear()` 方法来清空整个字典:
- my_dict = {'key1': 'value1', 'key2': 'value2'}
- # 使用del语句删除键值对
- del my_dict['key1']
- # 使用pop()方法删除键值对,并返回被删除的值
- removed_value = my_dict.pop('key2')
- # 清空字典
- my_dict.clear()
- # 改(修改键值对)
- my_dict = {'key1': 'value1'}
- my_dict['key1'] = 'new_value1' # 修改 'key1' 的值为 'new_value1'
- #查(查询键值对)
- # 可以通过键来查询字典中的值:
- my_dict = {'key1': 'value1', 'key2': 'value2'}
- # 使用键来获取值
- value = my_dict['key1'] # 如果键不存在,会抛出KeyError异常
- # 使用get()方法来安全地获取值,如果键不存在则返回None或指定的默认值
- value = my_dict.get('key1') # 如果键存在,返回对应的值;否则返回None
- value = my_dict.get('key3', 'default_value') # 如果键不存在,返回'default_value'
- # 通过 `in` 关键字来检查字典中是否包含某个键:
- key_exists = 'key1' in my_dict # 如果'key1'在字典中,返回True;否则返回False
- # 使用 `keys()`, `values()`, 和 `items()` 方法来获取字典的键、值或键值对的列表:
- keys = my_dict.keys() # 获取键的列表
- values = my_dict.values() # 获取值的列表
- items = my_dict.items() # 获取键值对的列表
-
- # 应用2:动态数据存储
- user_data = dict()
- print(user_data)
- user_data['name'] = 'Myelsa'
- user_data['age'] = 18
- print(user_data)
- # {}
- # {'name': 'Myelsa', 'age': 18}
-
- # 应用3:配置文件和参数设置
- config = dict(
- database_url='postgresql://user:password@localhost:5432/mydb',
- debug_mode=True
- )
- print(config)
- # {'database_url': 'postgresql://user:password@localhost:5432/mydb', 'debug_mode': True}
-
- # 应用4:统计数据
- word_counts = dict()
- text = "Myelsa is a sunny and handsome boy. Myelsa is wonderful!"
- for word in text.split():
- if word in word_counts:
- word_counts[word] += 1
- else:
- word_counts[word] = 1
- print(word_counts)
- # {'Myelsa': 2, 'is': 2, 'a': 1, 'sunny': 1, 'and': 1, 'handsome': 1, 'boy.': 1, 'wonderful!': 1}
-
- # 应用5:映射和转换
- abbreviations = dict(
- BTW='By the way',
- LOL='Laugh out loud'
- )
- text = "BTW, this is a LOL example."
- for abbr, expansion in abbreviations.items():
- text = text.replace(abbr, expansion)
- print(abbreviations)
- # {'BTW': 'By the way', 'LOL': 'Laugh out loud'}
-
- # 应用6:解析JSON数据
- import json
- json_data = '{"name": "Myelsa", "age": 18}'
- data_dict = json.loads(json_data)
- print(data_dict['name'])
- # Myelsa
-
- # 应用7:缓存和状态管理
- cache = dict()
- def compute_expensive_result(key):
- if key not in cache:
- cache[key] = some_expensive_computation(key)
- return cache[key]
-
- # 应用8:构建复杂数据结构
- users = {
- 'Myelsa': {
- 'age': 18,
- 'email': 'alice@example.com'
- },
- 'Jimmy': {
- 'age': 15,
- 'email': 'bob@example.com'
- }
- }
- print(users)
- # {'Myelsa': {'age': 18, 'email': 'alice@example.com'}, 'Jimmy': {'age': 15, 'email': 'bob@example.com'}}
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- Rem 模拟Python中dict()函数应用1:字典的增、删、改、查操作
- '你需要在VBA编辑器中添加对 Microsoft Scripting Runtime 的引用。你可以通过以下步骤来添加:
- '1、在VBA编辑器中,点击 "工具" -> "引用"
- '2、在弹出的 "引用 - VBAProject" 对话框中,滚动并勾选 "Microsoft Scripting Runtime"
- '3、点击 "确定"
- Rem 增(添加键值对)
- Sub TestRun_1()
- Dim my_dict As Object
-
- Set my_dict = CreateObject("Scripting.Dictionary")
- my_dict.add "key1", "value1"
- ' 打印键值对以验证
- Debug.Print my_dict.item("key1") ' 输出: value1
- End Sub
- 'value1
-
- Rem 删(删除键值对或字典)
- Sub TestRun_2()
- Dim my_dict As Object
- Set my_dict = CreateObject("Scripting.Dictionary")
-
- ' 添加键值对
- my_dict.add "key1", "value1"
- my_dict.add "key2", "value2"
- ' 打印字典的内容以验证
- Debug.Print "初始字典内容:"
- Debug.Print "key1 -> " & my_dict.item("key1")
- Debug.Print "key2 -> " & my_dict.item("key2")
- ' 使用Remove方法删除键值对
- my_dict.Remove ("key1")
- Debug.Print "删除key1后的字典内容:"
- If Not my_dict.Exists("key1") Then
- Debug.Print "key1已删除"
- End If
- ' 使用Item方法和Remove方法结合来模拟pop()方法,并返回被删除的值
- Dim removed_value As Variant
- If my_dict.Exists("key2") Then
- removed_value = my_dict.item("key2")
- my_dict.Remove ("key2")
- Debug.Print "使用pop()方法模拟删除key2,返回的值是:" & removed_value
- Else
- Debug.Print "key2不存在,无法pop"
- End If
- ' 清空字典
- my_dict.RemoveAll
- Debug.Print "清空字典后的内容:"
- If my_dict.count = 0 Then
- Debug.Print "字典已清空"
- End If
- End Sub
- '初始字典内容:
- 'key1 -> value1
- 'key2 -> value2
- '删除key1后的字典内容:
- 'key1已删除
- '使用pop()方法模拟删除key2,返回的值是:value2
- '清空字典后的内容:
- '字典已清空
-
- Rem 改(修改键值对)
- Sub TestRun_3()
- Dim my_dict As Object
- Set my_dict = CreateObject("Scripting.Dictionary")
-
- ' 添加键值对
- my_dict.add "key1", "value1"
- ' 修改 'key1' 的值为 'new_value1'
- my_dict("key1") = "new_value1"
- ' 打印修改后的值以验证
- Debug.Print "修改后的 'key1' 的值: " & my_dict.item("key1")
- End Sub
- '修改后的 'key1' 的值: new_value1
-
- Rem 查(查询键值对)
- Sub TestRun_4()
- Dim my_dict As Object
- Set my_dict = CreateObject("Scripting.Dictionary")
-
- ' 添加键值对
- my_dict.add "key1", "value1"
- my_dict.add "key2", "value2"
-
- ' 使用键来获取值
- Dim val As Variant
- On Error Resume Next ' 忽略因键不存在而可能产生的错误
- val = my_dict.item("key1")
- If Err.number <> 0 Then
- Debug.Print "KeyError: 键 'key1' 不存在"
- Err.Clear ' 清除错误
- Else
- Debug.Print "键 'key1' 的值: " & val
- End If
- On Error GoTo 0 ' 恢复正常的错误处理
-
- ' 使用类似get()的方法安全地获取值
- Dim val_1 As Variant
- val_1 = GetValueSafe(my_dict, "key1")
- Debug.Print "安全获取 'key1' 的值: " & IIf(IsMissing(val_1), "None", val_1)
-
- val_1 = GetValueSafe(my_dict, "key3", "default_value")
- Debug.Print "安全获取 'key3' 的值(带默认值): " & val_1
-
- ' 通过 `Exists` 方法来检查字典中是否包含某个键
- Dim key_exists As Boolean
- key_exists = my_dict.Exists("key1")
- Debug.Print "'key1' 是否存在于字典中: " & CStr(key_exists)
-
- ' 使用 `Keys()`, `Items()` 方法来获取字典的键和键值对的列表
- Dim keys As Variant
- Dim items As Variant
- Dim i As Integer
-
- keys = my_dict.keys()
- Debug.Print "键的列表: "
- For i = LBound(keys) To UBound(keys)
- Debug.Print keys(i)
- Next i
-
- items = my_dict.items()
- Debug.Print "键值对的列表: "
- For i = LBound(items) To UBound(items)
- Debug.Print "键: " & my_dict.keys()(i) & ", 值: " & items(i)
- Next i
-
- ' 获取值的列表
- Dim values As Variant
- ReDim values(UBound(items)) ' 预先分配数组大小
- For i = LBound(items) To UBound(items)
- values(i) = items(i)
- Next i
- Debug.Print "值的列表: "
- For i = LBound(values) To UBound(values)
- Debug.Print values(i)
- Next i
- End Sub
-
- Function GetValueSafe(dict As Object, key As Variant, Optional defaultValue As Variant = Empty) As Variant
- If dict.Exists(key) Then
- GetValueSafe = dict.item(key)
- Else
- GetValueSafe = defaultValue
- End If
- End Function
- '键 'key1' 的值: value1
- '安全获取 'key1' 的值: value1
- '安全获取 'key3' 的值(带默认值): default_value
- ''key1' 是否存在于字典中: True
- '键的列表:
- 'key1
- 'key2
- '键值对的列表:
- '键: key1 , 值: Value1
- '键: key2 , 值: Value2
- '值的列表:
- 'Value1
- 'Value2
-
- Rem 模拟Python中dict()函数应用2:动态数据存储
- Sub TestRun_5()
- ' 声明一个Scripting.Dictionary对象
- Dim user_data As Object
- ' 创建Scripting.Dictionary对象
- Set user_data = CreateObject("Scripting.Dictionary")
-
- ' 打印初始的字典(VBA中无法直接打印字典,但可以打印其项数)
- Debug.Print "初始的user_data字典(项数): " & user_data.count
-
- ' 添加键值对
- user_data.add "name", "Myelsa"
- user_data.add "age", 18
-
- ' 打印更新后的字典(VBA中无法直接打印整个字典,但可以遍历并打印其键值对)
- Debug.Print "更新后的user_data字典:"
- Dim key As Variant
- For Each key In user_data.keys
- Debug.Print "键: " & key & ", 值: " & user_data(key)
- Next key
- End Sub
- '初始的user_data字典(项数): 0
- '更新后的user_data字典:
- '键: name, 值: Myelsa
- '键: age, 值: 18
-
- Rem 模拟Python中dict()函数应用3:配置文件和参数设置
- Sub TestRun_6()
- ' 声明Scripting.Dictionary对象
- Dim config As Object
- ' 创建Scripting.Dictionary对象
- Set config = CreateObject("Scripting.Dictionary")
-
- ' 添加键值对
- config.add "database_url", "postgresql://user:password@localhost:5432/mydb"
- config.add "debug_mode", True
-
- ' 打印字典内容
- Debug.Print "Config 字典内容:"
- Dim key As Variant
- For Each key In config.keys
- ' 对于布尔值,我们需要特殊处理以在VBA中正确显示
- Dim value As Variant
- value = config(key)
- If VBA.IsNumeric(value) Then
- Debug.Print "键: " & key & ", 值: " & IIf(value, "True", "False")
- Else
- Debug.Print "键: " & key & ", 值: " & CStr(value)
- End If
- Next key
- End Sub
- 'config 字典内容:
- '键: database_url, 值: postgresql://user:password@localhost:5432/mydb
- '键: debug_mode, 值: True
-
- Rem 模拟Python中dict()函数应用4:统计数据
- Sub TestRun_7()
- ' 声明Scripting.Dictionary对象来存储单词计数
- Dim word_counts As Object
- ' 声明变量来存储文本
- Dim text As String
- ' 声明变量来存储分割后的单词
- Dim words As Variant
- ' 声明变量来存储当前单词
- Dim word As Variant
- ' 声明变量来存储单词的计数
- Dim count As Integer
-
- ' 创建Scripting.Dictionary对象
- Set word_counts = CreateObject("Scripting.Dictionary")
-
- ' 设置文本内容
- text = "Myelsa is a sunny and handsome boy. Myelsa is wonderful!"
-
- ' 使用Split函数按空格分割文本为单词数组
- words = Split(text, " ")
-
- ' 遍历单词数组
- For Each word In words
- ' 忽略大小写并去除单词两端的空白字符
- word = Trim(LCase(word))
-
- ' 如果单词已经在字典中,则增加计数
- If word_counts.Exists(word) Then
- word_counts(word) = word_counts(word) + 1
- ' 否则,将单词添加到字典并设置计数为1
- Else
- word_counts.add word, 1
- End If
- Next word
-
- ' 打印单词计数
- Debug.Print "单词计数:"
- Dim key As Variant
- For Each key In word_counts.keys
- Debug.Print "单词: " & key & ", 计数: " & word_counts(key)
- Next key
- End Sub
- 单词计数:
- '单词: myelsa, 计数: 2
- '单词: is, 计数: 2
- '单词: a, 计数: 1
- '单词: sunny, 计数: 1
- '单词: and, 计数: 1
- '单词: handsome, 计数: 1
- '单词: boy., 计数: 1
- '单词: wonderful!, 计数: 1
-
- Rem 模拟Python中dict()函数应用5:映射和转换
- Sub TestRun_8()
- ' 声明Scripting.Dictionary对象来存储缩写和对应的扩展
- Dim abbreviations As Object
- ' 声明变量来存储文本
- Dim text As String
- ' 声明变量来存储缩写和扩展
- Dim abbr As Variant
- Dim expansion As Variant
-
- ' 创建Scripting.Dictionary对象
- Set abbreviations = CreateObject("Scripting.Dictionary")
- ' 添加缩写和对应的扩展
- abbreviations.add "BTW", "By the way"
- abbreviations.add "LOL", "Laugh out loud"
- ' 设置文本内容
- text = "BTW, this is a LOL example."
- ' 遍历字典中的缩写和扩展
- For Each abbr In abbreviations.keys
- expansion = abbreviations(abbr)
- ' 使用Replace函数替换文本中的缩写
- text = Replace(text, abbr, expansion)
- Next abbr
- ' 打印替换后的文本
- Debug.Print "替换后的文本:" & text
- ' 打印缩写和扩展的字典(在VBA中不能直接打印字典,但可以打印其内容)
- Debug.Print "缩写和扩展的字典:"
- For Each abbr In abbreviations.keys
- Debug.Print "缩写: " & abbr & ", 扩展: " & abbreviations(abbr)
- Next abbr
- End Sub
- '替换后的文本:By the way, this is a Laugh out loud example.
- '缩写和扩展的字典:
- '缩写: BTW, 扩展: By the way
- '缩写: LOL, 扩展: Laugh out loud
-
- Rem 模拟Python中dict()函数应用8:构建复杂数据结构
- Sub TestRun_9()
- ' 声明Scripting.Dictionary对象来存储用户信息
- Dim users As Object
- ' 声明变量来存储用户名称和用户的详细信息字典
- Dim userName As Variant
- Dim userInfo As Object
- ' 声明变量来存储用户的年龄和邮箱
- Dim age As Integer
- Dim email As String
-
- ' 创建Scripting.Dictionary对象来存储用户信息
- Set users = CreateObject("Scripting.Dictionary")
- ' 添加第一个用户信息
- Set userInfo = CreateObject("Scripting.Dictionary")
- age = 18
- email = "alice@example.com"
- userInfo.add "age", age
- userInfo.add "email", email
- users.add "Myelsa", userInfo
- ' 添加第二个用户信息
- Set userInfo = CreateObject("Scripting.Dictionary")
- age = 15
- email = "bob@example.com"
- userInfo.add "age", age
- userInfo.add "email", email
- users.add "Jimmy", userInfo
- ' 打印用户信息
- Debug.Print "用户信息:"
- For Each userName In users.keys
- Debug.Print "用户名: " & userName
- Dim userInfoKey As Variant
- For Each userInfoKey In users(userName).keys
- Debug.Print " " & userInfoKey & ": " & users(userName)(userInfoKey)
- Next userInfoKey
- Next userName
- End Sub
- '用户信息:
- '用户名: Myelsa
- ' age: 18
- 'email: alice@ example.com
- '用户名: Jimmy
- ' age: 15
- 'email: bob@ example.com
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
1、dict():
在Python中,dict()函数用于创建字典对象,其优点和缺点主要与字典这种数据结构本身相关。
1-1、优点:
1-1-1、快速访问:字典提供了基于键的快速查找、插入和删除操作。由于字典底层是通过哈希表实现的,所以这些操作的时间复杂度平均情况下是O(1),这使得字典在处理大量数据时非常高效。
1-1-2、灵活性:字典允许存储任意类型的键和值,只要键是可哈希的(即具有不变性并能生成唯一的哈希值)。这种灵活性使得字典能够轻松适应各种应用场景。
1-1-3、存储关联数据:字典非常适合存储具有关联关系的数据,如配置信息、映射关系等。通过键可以方便地获取或修改与之关联的值。
1-1-4、动态性:字典的大小可以动态调整,可以根据需要添加或删除键值对,无需预先定义大小。
1-2、缺点:
1-2-1、无序性:在Python 3.6之前的版本中,字典是无序的,即键值对的存储顺序是不确定的。虽然从Python 3.7开始,字典保持了插入顺序,但它仍然不是一个有序的集合类型。如果需要保持顺序,可能需要额外的处理或使用其他数据结构。
1-2-2、空间开销:由于字典使用哈希表来存储键值对,因此相对于列表等其他数据结构,字典可能会占用更多的内存空间。特别是在存储大量数据时,这种空间开销可能会变得更加显著。
1-2-3、键的唯一性:字典要求键必须是唯一的。如果尝试使用相同的键多次添加元素,后添加的值会覆盖先前的值。这可能会在某些情况下导致数据丢失或意外覆盖。
1-2-4、哈希冲突:虽然哈希表的设计旨在减少哈希冲突,但在极端情况下,如果哈希函数的设计不够理想或键的分布不均匀,哈希冲突可能会导致性能下降。
注意,这些优缺点是针对字典这种数据结构本身而言的,而不是针对dict()函数本身。dict()函数只是用于创建字典对象的一个简单工具,其性能和行为与字典数据结构本身是一致的。因此,在选择使用字典时,应充分考虑其优缺点,并根据具体的应用场景和需求来决定是否使用。
2、dict:
2-1、优点:
Python中的字典(dictionary)类型是一种非常强大且灵活的数据结构,用于存储键值对。
2-1-1、快速访问:字典的查找、插入和删除操作的时间复杂度接近于O(1),即平均情况下,无论字典有多大,这些操作都能在常数时间内完成。这使得字典成为存储需要频繁查找的数据的理想选择。
2-1-2、灵活性:字典允许存储任何类型的键和值,只要键是可哈希的(即具有不变性,并且可以通过哈希函数得到唯一的哈希值)。这意味着你可以在一个字典中存储各种类型的数据,如整数、字符串、浮点数、列表、元组、其他字典等。
2-1-3、无序性:在Python 3.7及更高版本中,字典保持了插入顺序(尽管它仍然不是一个有序的集合类型)。这种特性在某些场景下很有用,比如当你需要按特定顺序遍历字典时。
2-1-4、易于使用:字典的语法直观易懂,创建和修改字典的操作也非常简单。
2-1-5、可扩展性:字典的大小可以动态调整,你可以根据需要添加或删除键值对,而无需预先定义字典的大小。
2-2、缺点:
2-2-1、无序性:在Python 3.6及之前的版本中,字典是无序的,这意味着你不能预测键值对的存储顺序。虽然这通常不是问题,但在需要按特定顺序处理键值对的情况下,它可能会导致问题。
2-2-2、空间开销:由于字典需要维护哈希表和存储键值对,因此相对于列表等其他数据结构,字典可能会占用更多的内存空间。
2-2-3、键的唯一性:字典要求键必须是唯一的。如果尝试使用相同的键多次添加元素,后添加的值会覆盖先前的值。这可能会在某些情况下导致数据丢失或意外覆盖。
2-2-4、哈希冲突:虽然字典的查找、插入和删除操作在平均情况下具有O(1)的时间复杂度,但在最坏情况下(即哈希冲突很多时),这些操作的时间复杂度可能会退化。虽然Python的字典实现通过开放寻址等技术减少了哈希冲突的影响,但在极端情况下仍可能出现问题。
2-2-5、不可变性:字典本身是不可变的,但字典的值可以是可变的。这可能会导致在并发编程中出现问题,因为多个线程或进程可能同时修改同一个字典的值,从而引发数据不一致或竞争条件。
注意,这些优缺点是相对于其他数据结构而言的,而不是绝对的。在选择使用字典还是其他数据结构时,应根据具体的应用场景和需求来权衡这些优缺点。
Python算法之旅:Myelsa的Python算法之旅(高铁直达)-CSDN博客
Python函数之旅:Myelsa的Python函数之旅(高铁直达)
欢迎志同道合者一起交流学习,我的QQ:94509325/微信:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。