我正在尝试在字典中创建字典,但字典总是以相同的细节结束。
以下是代码:
Class DailyStatement(object):
def __init__(self):
self.masterdict={}
self.subdict={}
self.list_of_subdicts=['yesterday','today']
self.keys=['high','low','open','close']
self._create_masterdict()
def _create_masterdict(self):
for subdict in self.list_of_subdicts:
self.masterdict[subdict]={}
self.masterdict[subdict]=self.create_subdict(subdict)
print self.masterdict[subdict]
def create_subdict(self,subdict):
for item in self.keys:
subdict[item]=self.get_value(item,subdict)
return self.subdict
def get_value(self,item,subdict):
{code to find the value}
return value
我跑的时候:
ds=DailyStatement()
它打印得很好,看起来效果很好,在控制台上显示:
{'high':2,'low':1,'open':1.5,'close':1.6}
{'high':2.2,'low':2.1,'open':2.5,'close':2.6}
但是当我跑步时:
print ds.masterdict
我明白了:
{'today':{'high':2,'low':1,'open':1.5,'close':1.6},
'yesterday':{'high':2,'low':1,'open':1.5,'close':1.6}}
我无法理解为什么会这样。它似乎在启动Class
时构建了masterdict,但在代码运行之后是dictionary
重写本身?
过去几个小时我一直在关注这个问题,似乎无法弄明白。
非常感谢任何帮助。
答案 0 :(得分:1)
您正在将self.subdict
用于两个子词典。你应该做的是每次需要时创建一个新的子字典:
import random
class DailyStatement(object): # changed from C to c
def __init__(self): # Added self
self.masterdict={}
# Removed self.subdict
self.list_of_subdicts=['yesterday', 'today']
self.keys=['high', 'low', 'open', 'close']
self._create_masterdict()
def _create_masterdict(self):
for subdict in self.list_of_subdicts:
self.masterdict[subdict] = {}
self.masterdict[subdict] = self.create_subdict(subdict) # added self
print self.masterdict[subdict]
def create_subdict(self, subdict):
sub_dict = {}
for item in self.keys:
sub_dict[item] = self.get_value(item, subdict) # added self
return sub_dict
def get_value(self, item, subdict): # added self
return random.randrange(1,4)
if __name__ == "__main__":
ds=DailyStatement()
print ds.masterdict
我已就其他变化发表评论。
这是python repl中的一个简单示例:
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> y = {}
>>> x = y
>>> y["NOEL"] = "ROCKS"
>>> x
{'NOEL': 'ROCKS'}
>>>
您可以观察到x从未直接设置,但仍包含添加到y的键和值。