python - 无法更新词典

标签 python dictionary

我在尝试编写数独求解器时遇到了这个问题(其中一些部分引用了 http://norvig.com/sudoku.html )

这是我迄今为止引用上述 URL 编写的代码。

puzzle = '003198070890370600007004893030087009079000380508039040726940508905800000380756900'
cell = '123456789'
cell_break = ['123','456','789']


def generate_keys(A, B):
  "Cross product of elements in A and elements in B."
  return [a+b for a in A for b in B]

#print generate_keys(cell,cell)

def dict_puzzle(puzzle,cell):
  'Making a dictionary to store the key and values of the puzzle'
  trans_puzzle = {}
  key_list = generate_keys(cell,cell)
  i=0
  for x in puzzle:
    trans_puzzle[str(key_list[i])] = x
    i = i + 1
    return trans_puzzle

dict_puzzle(puzzle,cell)['11'] = 'die'
print dict_puzzle(puzzle,cell)['11']

对于代码的最后两行,我尝试更改字典但无济于事。它只是返回 0,这是原始值。 (即突变未成功)

我不知道为什么会发生这种情况:(

最佳答案

您再次调用该函数,因此它返回一个新字典。您需要将第一次调用的结果分配给一个变量并改变它。

result = dict_puzzle(puzzle,cell)
result['11'] = 'die'
print(result)

关于python - 无法更新词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964791/

相关文章:

python - tkinter 调用两个函数

python - 在 python 中从 TIMIT 数据库读取 WAV 文件

python - Seaborn X 轴分类数据

Python,在(a,b)对列表中找到具有最大总和(b值)的a值

c# - 使用 EqualityComparer 初始化静态字典

vba 字典 - 从 Items() 返回 KEY

python - 如何过滤具有给定键匹配值的字典列表

python - Pandas read_fwf : specify dtype

Python 从字典中删除值适合函数的项目?

python - 按赢家/输家名称查询体育数据的数据框,并获取每个玩家的汇总统计表?