【问题标题】:Changing only one value of a key in a dictionary that has multiple values仅更改具有多个值的字典中键的一个值
【发布时间】:2017-04-02 01:29:46
【问题描述】:

我有一个分配了多个值的键。我想要求用户输入 (new_population),并替换键中的旧值 (current_population)。我希望键 (num) 中的其他值不受影响。

current_population = 5 
num = 3
dict = {}
dict["key"] = [current_population, num]

new_population = input("What is the new population?")

说(例如清酒),new_population 的值为 10。我的目标是最终输出:

{'key': [10, 3]}

我该怎么做呢?

【问题讨论】:

  • 你知道 dict 是一个内置对象吗?不要将变量名用作 dict 以防万一您的模块/代码的其他部分需要内置函数
  • 是的,我愿意。回想起来,我应该使用不同的名称,但我只是认为这是说它是字典的最明显方式。

标签: python dictionary key


【解决方案1】:

需要明确的是,您实际上拥有的是一个字典,其中每个元素都是一个列表。不可能有多个元素具有相同的键,因为这会产生未定义的行为(查找将返回哪个元素?)。如果你这样做了

current_population = 5 
num = 3
mydict = {}
mydict["key"] = [current_population, num]
elem = mydict["key"]
print elem

您会看到elem 实际上是列表 [5,3]。因此,要获取或设置任一值,您需要将索引到从索引到字典中获得的列表中。

mydict["key"][0] = new_population

(就像在接受的答案中一样)。

如果您不想跟踪哪个索引是人口,哪个是数字,您可以制作一个字典字典:

mydict = {}
mydict["key"] = {"pop": current_population, "num", num}
mydict["key"]["pop"] = new_population

【讨论】:

    【解决方案2】:
    dict["key"][0] = new_population
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 2011-06-09
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多