Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么要更新所有字典键值,而不仅仅是我指定的键值?_Python_Dictionary - Fatal编程技术网

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}