文章目录
- person = {“name”: “Alice”, “age”: 25, “city”: “Shanghai”} print(person[“name”]) # 输出:Alice
- 字典的查找速度极快,时间复杂度为 O(1)。相比 list 的 O(n),处理大量数据时优势明显。
- squares = {x: x*x for x in range(1, 6)} print(squares) # 输出:{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
- person = {“name”: “Alice”, “age”: 25} score = person.get(“score”, 0) print(score) # 输出:0
- a = {“x”: 1, “y”: 2} b = {“y”: 3, “z”: 4} c = {**a, **b} print(c) # 输出:{‘x’: 1, ‘y’: 3, ‘z’: 4}
- dict (字典)是不允许一个键创建两次的,但是在创建 dict (字典)的时候如果出现了一个键值赋予了两次,会以最后一次赋予的值为准 dict (字典)键必须不可变,可是键可以用数字,字符串或元组充当,但是就是不能使用列表
- 方法和函数 描述 len(dict) 计算字典元素个数 str(dict) 输出字典可打印的字符串表示 type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型 dict.clear() 删除字典内所有元素 dict.copy() 返回一个字典的浅复制 dict.values() 以列表返回字典中的所有值 popitem() 随机返回并删除字典中的一对键和值 dict.items() 以列表返回可遍历的(键, 值) 元组数组
- set1=set([123,456,789]) print(set1) fruits = {“apple”, “banana”, “orange”} fruits.add(“pear”) print(fruits)
- nums = [1, 2, 2, 3, 4, 4, 5] unique_nums = set(nums) print(unique_nums) # 输出:{1, 2, 3, 4, 5}
- 交集:& 并集:| 差集:- a = {1, 2, 3} b = {2, 3, 4} print(a & b) # 输出:{2, 3} print(a | b) # 输出:{1, 2, 3, 4} print(a – b) # 输出:{1}
- even = {x for x in range(10) if x % 2 == 0} print(even) # 输出:{0, 2, 4, 6, 8}
目录
- 一、Dict(字典):键值对的魔法
- 1. 基本用法(创建和访问)
- 2. 字典的高效查找
- 3. 字典推导式
- 4. get() 方法,优雅处理 KeyError
- 5. 合并字典的正确姿势
- 6.注意事项
- 7.dict (字典) 的函数和方法
- 二、Set(集合):去重与高效运算的利器
- 1. 基本用法(创建)
- 2. 集合去重
- 3. 集合的高效运算
- 4. 集合推导式
- 三、总结
person = {"name": "Alice", "age": 25, "city": "Shanghai"}
print(person["name"]) # 输出:Alice
字典的查找速度极快,时间复杂度为 O(1)。相比 list 的 O(n),处理大量数据时优势明显。
squares = {x: x*x for x in range(1, 6)}
print(squares) # 输出:{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
person = {"name": "Alice", "age": 25}
score = person.get("score", 0)
print(score) # 输出:0
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
c = {**a, **b}
print(c) # 输出:{'x': 1, 'y': 3, 'z': 4}
- dict (字典)是不允许一个键创建两次的,但是在创建 dict (字典)的时候如果出现了一个键值赋予了两次,会以最后一次赋予的值为准
- dict (字典)键必须不可变,可是键可以用数字,字符串或元组充当,但是就是不能使用列表
| 方法和函数 | 描述 |
|---|---|
| len(dict) | 计算字典元素个数 |
| str(dict) | 输出字典可打印的字符串表示 |
| type(variable) | 返回输入的变量类型,如果变量是字典就返回字典类型 |
| dict.clear() | 删除字典内所有元素 |
| dict.copy() | 返回一个字典的浅复制 |
| dict.values() | 以列表返回字典中的所有值 |
| popitem() | 随机返回并删除字典中的一对键和值 |
| dict.items() | 以列表返回可遍历的(键, 值) 元组数组 |
set1=set([123,456,789])
print(set1)
fruits = {"apple", "banana", "orange"}
fruits.add("pear")
print(fruits)
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = set(nums)
print(unique_nums) # 输出:{1, 2, 3, 4, 5}
- 交集:
&
- 并集:
|
- 差集:
-
a = {1, 2, 3}
b = {2, 3, 4}
print(a & b) # 输出:{2, 3}
print(a | b) # 输出:{1, 2, 3, 4}
print(a - b) # 输出:{1}
&|-
even = {x for x in range(10) if x % 2 == 0}
print(even) # 输出:{0, 2, 4, 6, 8}
Dict 适合存储映射关系,查找速度极快
Set 适合去重和集合运算,效率高
掌握推导式、合并、去重等技巧,让你的代码更 Pythonic!
到此这篇关于你必须知道的Python Dict和Set实用技巧分享的文章就介绍到这了,更多相关Python Dict和Set技巧内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- Python基础之dict和set的使用详解
- Python中的 Set 与 dict
- python-字典dict和集合set
- python–字典(dict)和集合(set)详解
- Python中dict和set的用法讲解
- 详解Python中dict与set的使用