Skip to main content
 首页 » 编程设计

python之仅更改具有多个值的字典中键的一个值

2025年02月15日8freeliver54

我有一个分配了多个值的键。我想要求用户输入 (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]} 

我该怎么做?

请您参考如下方法:

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

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

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

mydict["key"][0] = new_population 

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

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

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