{}
表示。
# 定义字典的多种方式
d1 = {'name': 'Alice', 'age': 20}
d2 = dict(name='Bob', age=22)
d3 = dict([('gender', 'male'), ('score', 90)])
empty_dict = {}
d['key'] = value
del d['key']
、pop()
in
keys()
、values()
、items()
# 访问和操作字典
d = {'name': 'Alice', 'age': 20}
print(d['name']) # Alice
print(d.get('age')) # 20
d['gender'] = 'female'
d['age'] = 21
d.pop('name')
print(d)
# 遍历所有键
for k in d:
print(k, d[k])
# 遍历所有项
for k, v in d.items():
print(k, v)
# 获取所有键、值、项
print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))
# 字典推导式
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# setdefault用法
d = {'name': 'Alice'}
d.setdefault('age', 18)
print(d)
dict.copy()
dict1.update(dict2)
或 {**dict1, **dict2}
# 合并字典
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
merged = {**d1, **d2}
print(merged) # {'a': 1, 'b': 3, 'c': 4}
# 统计单词出现次数
words = ['apple', 'banana', 'apple', 'orange']
count = {}
for w in words:
count[w] = count.get(w, 0) + 1
print(count)
# 嵌套字典存储学生信息
students = {
'Tom': {'age': 18, 'score': 90},
'Jerry': {'age': 19, 'score': 85}
}
print(students['Tom']['score']) # 90
import json
d = {'name': 'Alice', 'age': 20}
json_str = json.dumps(d)
print(json_str)
print(json.loads(json_str))
# 创建集合
set1 = {1, 2, 3, 4}
set2 = set([1, 2, 2, 3, 3, 4]) # 自动去重
set3 = set('hello')
empty_set = set()
add(x)
、update(iterable)
remove(x)
、discard(x)
、pop()
、clear()
# 添加和删除元素
set1.add(5)
set1.update([6, 7])
set1.remove(2)
set1.discard(10) # 不报错
set1.pop()
set1.clear()
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 交集
print(set1 & set2)
# 并集
print(set1 | set2)
# 差集
print(set1 - set2)
# 对称差集
print(set1 ^ set2)
issubset()
、issuperset()
、==
、!=
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b)) # True
print(b.issuperset(a)) # True
print(a == {2, 1}) # True
frozenset
创建不可变集合,可作为字典的键。
fs = frozenset({1, 2, 3})
dict_with_frozenset = {fs: 'immutable set'}
numbers = [1, 2, 2, 3, 3, 4]
unique_numbers = list(set(numbers))
print(unique_numbers)
# 判断元素是否存在
s = {'apple', 'banana', 'orange'}
print('apple' in s) # True
students_math = {'Alice', 'Bob', 'Charlie', 'David'}
students_physics = {'Bob', 'Charlie', 'Eve', 'Frank'}
# 同时学习数学和物理的学生
both = students_math & students_physics
print(both)
# 只学习数学的学生
only_math = students_math - students_physics
print(only_math)
set()
,{}
是空字典# 错误示例
# invalid_dict = {[1,2]: 'list'} # TypeError
# set1 = {1, [2,3]} # TypeError
empty_set = set()
empty_dict = {}
print(type(empty_set)) #
print(type(empty_dict)) #
# 统计文本中每个单词出现的次数
def word_frequency(text):
words = text.lower().split()
freq = {}
for word in words:
word = word.strip('.,!?;:')
if word:
freq[word] = freq.get(word, 0) + 1
return freq
text = "Hello world! Hello Python. Python is great!"
print(word_frequency(text))
# 简单英汉词典
dict_en_cn = {'apple': '苹果', 'banana': '香蕉', 'cat': '猫'}
word = 'apple'
print(f"{word} 的中文是: {dict_en_cn.get(word, '未收录')}")
# 两个列表的共同元素和不同元素
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common = set(list1) & set(list2)
diff = set(list1) ^ set(list2)
print(f"共同元素: {common}")
print(f"不同元素: {diff}")
实现一个学生成绩管理系统,要求支持:
编写一个程序,读取一段英文文本,统计每个单词出现的次数,并输出出现频率最高的前10个单词。
实现一个集合运算工具,支持输入两个集合,输出它们的交集、并集、差集和对称差集。