【问题标题】:Dictionary won't update value from a variable [duplicate]字典不会更新变量的值[重复]
【发布时间】:2021-10-31 17:05:03
【问题描述】:

我的代码如下所示:

firstValue = "First Value Key"
secondValue = "Second Value Key"
thirdValue = "Third Value Key"

Dictionary = {"0":firstValue,
              "1":secondValue,
              "2":thirdValue}

print(Dictionary["0"])

firstValue = "New Value"

print(Dictionary["0"])

输出如下:

First Value Key
First Value Key

我希望输出看起来像这样:

First Value Key
New Value

我错过了什么?

【问题讨论】:

标签: python dictionary pointers variables


【解决方案1】:

你只是改变你已经传入字典的变量,直接更新它的值:

Dictionary['0'] = "New Value"

【讨论】:

  • 你应该改用变量值
【解决方案2】:

需要将变量的值赋给字典值:

firstValue = "First Value Key"
secondValue = "Second Value Key"
thirdValue = "Third Value Key"

Dictionary = {"0":firstValue,
              "1":secondValue,
              "2":thirdValue}

print(Dictionary["0"])

firstValue = "New Value"
Dictionary["0"] = firstValue
print(Dictionary["0"])

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 2020-02-24
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    相关资源
    最近更新 更多