我的目标:
{0: {'0':'0', '1':'1'), 1: {'0':'2', '1':'3'}, 2: {'0':'4','1':'0'}, 3:{'0':'1','1':'2'}, 4:{'0':'3' ,'1':'4' }}
我正在得到什么:
{0: {'1': '1'}, 1: {'1': '3'}, 2: {'1': '0'}, 3: {'1': '2'}, 4: {'1': '4'}}
因此,它仅存储'1'部分并覆盖'0'部分,但是我不确定如何解决此问题,因为我似乎读过的所有内容都说它应该更新(如果存在)或创建(如果不存在)。 几点注意:状态是0到4,字母是['0','1']值只是文本文件中的单个字符。
这是我的代码:
for state in range(0, numStates):
for letter in alphabet:
value = DFAFileLines[state+3].split()[alphabet.index(letter)]
print("State: " + str(state) + " Letter: " + letter +" Value: " + value)
itemDict = dict()
itemDict[letter] = value
transitionTable[state] = itemDict
答案 0 :(得分:0)
因此,当最终定义字典时,我最终不得不在字典中添加默认值,并且效果很好。 (请注意,这是我尝试过的代码的先前版本,而不是发布时的版本)。这是更新的代码:
transitionTable = dict(dict())
for state in range(0, numStates):
transitionTable[state] = {k: 0 for k in alphabet}
for state in range(0, numStates):
for letter in alphabet:
value = DFAFileLines[state+3].split()[alphabet.index(letter)]
stateDict = transitionTable[state]
stateDict[letter] = value
我本来拥有的与众不同之处
transitionTable[state] = {k for k in alphabet}
现在
transitionTable[state] = {k: 0 for k in alphabet}
答案 1 :(得分:0)
原始代码的问题是,您每次都要通过内部循环来重置itemDict
,并且还应该为状态键在每个外部for循环中分配一次transitionTable
for state in range(0, numStates):
itemDict = dict()
for letter in alphabet:
value = DFAFileLines[state+3].split()[alphabet.index(letter)]
print("State: " + str(state) + " Letter: " + letter +" Value: " + value)
itemDict[letter] = value
transitionTable[state] = itemDict