python dict.fromkeys方法的坑
今天在排查bug的时候踩了一个dict.fromkeys方法的坑,mark一下。业务逻辑中有一段用到了dict.fromkeys创建初始值为空列表的字典,之后根据不同key更新列表内容,类似下面的示例:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class_list = ['class01', 'calss02', 'class03']
total_info = dict.fromkeys(class_list, ['teacher_wang'])
print(total_info) # {'class01': ['teacher_wang'], 'calss02': ['teacher_wang'], 'class03': ['teacher_wang']}
for key, value in total_info.items():
print(id(value))
# 创建的total_info 的value值指向同一块内存空间,这就有些类似浅拷贝了
total_info['class01'].append('student_lihua')
print(total_info) # {'class01': ['teacher_wang', 'student_lihua'], 'calss02': ['teacher_wang', 'student_lihua'], 'class03': ['teacher_wang', 'student_lihua']}
如何解决这个方法?使用字典生成表达式来初始化字典值为空列表的字典,如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class_list = ['class01', 'calss02', 'class03']
total_info = {key: [] for key in class_list}
total_info['class01'].append('teacher_wang')
print(total_info) # {'class01': ['teacher_wang'], 'calss02': [], 'class03': []}