Python 为什么要更新所有字典键值,而不仅仅是我指定的键值?
我有一本以日期为主要名称的词典:Python 为什么要更新所有字典键值,而不仅仅是我指定的键值?,python,dictionary,Python,Dictionary,我有一本以日期为主要名称的词典: dateDict = dict.fromkeys(newDateRange,[]) 输出: 我还有以下课程: class attendance: def matchDate(self): if self.datein date_dict: date_dict[self.date].extend(self.names) def __init__(self, names, date):
dateDict = dict.fromkeys(newDateRange,[])
输出:
我还有以下课程:
class attendance:
def matchDate(self):
if self.datein date_dict:
date_dict[self.date].extend(self.names)
def __init__(self, names, date):
self.tickers = names
self.date= date
我的想法是在self.date中有一个与dateDict中的键名格式相同的对象。例如,self.date应该是“2021-02-09”,dateDic中的某个地方有一个键,也称为“2021-02-09”。但是,每当我运行代码时,对象都会用它的值(而不是我试图指定的值)更新两个键
在:
输出:
而不仅仅是:
{'2021-02-09': ['Billy','Kyle','Joe','Ashley'], '2021-02-08': []}
dict.from_keys()
使用的列表与所有键的值相同
改用字典
dateDict = {key: [] for key in newDateRange}
每个字典键都有与其值完全相同的列表<出于这个原因,code>dict.fromkeys()对于可变值基本上是无用的。这现在是有意义的。非常感谢。
{'2021-02-09': ['Billy','Kyle','Joe','Ashley'], '2021-02-08': ['Billy','Kyle','Joe','Ashley']}
{'2021-02-09': ['Billy','Kyle','Joe','Ashley'], '2021-02-08': []}
dateDict = {key: [] for key in newDateRange}