1. 字典(dict)
字典是一系列键值对
1.1 创建字典
# 空字典
person = {}
# 添加 or 更新键值对
person['name'] = 'Alice'
print(person)
person = {'name': 'Alice', 'age': 25}
languages = {
'Alice': ['Java', 'Python'],
'Alan': ['Python'],
'Tom': ['Go', 'Java']
}
1.2 访问字典值
alien = {
'color': 'green',
'points': 5
}
print(f'alien["color"]:{alien["color"]}, alien["points"]:{alien["points"]}')
当 key 不存在时,会报错 KeyError
print(alien['other'])
# KeyError: 'other'
改进 get(key, default)
key: 键,必填
default:键不存在时返回的默认值,可选
other = alien.get('other')
other_default = alien.get('other', 'not exist')
other_default2 = alien.get('other', '')
print(f'other: {other}, other_default: {other_default}')
1.3 字典操作
字典是一种动态结构,可随时在其中添加键值对
alien = {}
alien['x_point'] = 0
alien['y_point'] = 10
alien['name'] = 'axis'
# 删除键值对
del alien['name']
1.4 字典遍历
def dict_loop():
languages = {
'Alice': 'Java',
'Alan': 'Python',
'Tom': 'Go'
}
# 遍历字典
for item in languages.items():
print(item)
for i, item in enumerate(languages.items()):
print(i, item)
for key, value in languages.items():
print(f'key: {key}, value: {value}')
# 遍历键
for key in languages.keys():
print(f'key: {key.title()}')
# 等价,省略 .keys()
for key in languages:
print(key.title())
# 遍历值
for value in languages.values():
print(value)
1.5 排序
languages = {
'Alice': 'Java',
'Alan': 'Python',
'Tom': 'Go'
}
if 'Alan' in languages.keys():
print('Alan is in languages.keys() \n')
# 排序,sorted(*args) 不会修改原数据
sorted_languages = sorted(languages.keys())
print(sorted_languages)
duplicate_data = ['aaa', 'bbb', 'aaa', 'ccc']
# set去重(不保证原顺序)
set_data = set(duplicate_data)
print(set_data)
print(duplicate_data)
# 保留插入顺序(Python 3.7+)
unique_data = list(dict.fromkeys(duplicate_data))
print(unique_data)
print(duplicate_data)
1.6 字典集合
aliens = []
for e in range(3):
new_alien = {'color': 'green', 'points': e}
aliens.append(new_alien)
print(aliens)
[
{'color': 'green', 'points': 0},
{'color': 'green', 'points': 1},
{'color': 'green', 'points': 2}
]
1.7 字典中存储 对象 + 列表
languages = {
'Alice': ['Java', 'Python'],
'Alan': ['Python'],
'Tom': ['Go', 'Java']
}
for key, item in languages.items():
print(f'key: {key}, item: {item}')
for e in item:
print('\t', e)
1.8 字典中存储字典
users = {
'Alan': {
'career': 'Master',
'language': 'Python'
},
'Alice': {
'career': 'Programmer',
'language': 'Java'
}
}
print(users.get('Alan'))
for key, item in users.items():
print(f'key: {key}, career: {item.get("career")}, language: {item.get("language")}')