Python 在具有多个值的字典中只更改键的一个值

Python 在具有多个值的字典中只更改键的一个值,python,dictionary,key,Python,Dictionary,Key,我有一个指定了多个值的键。我想请求用户输入(新的_填充),并替换键中的旧值(当前_填充)。我希望键(num)中的其他值不受影响 current_population = 5 num = 3 dict = {} dict["key"] = [current_population, num] new_population = input("What is the new population?") 比如说(比如说),新人口的价值是10。我的目标是最终输出: {'key': [10, 3]}

我有一个指定了多个值的键。我想请求用户输入(新的_填充),并替换键中的旧值(当前_填充)。我希望键(num)中的其他值不受影响

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

new_population = input("What is the new population?")
比如说(比如说),新人口的价值是10。我的目标是最终输出:

{'key': [10, 3]}

我该怎么做呢?

说得很清楚,你实际上拥有的是一个字典,其中每个元素都是一个列表。不可能有多个元素具有相同的键,因为这将创建未定义的行为(查找将返回哪个元素?)。如果你这样做

dict["key"][0] = new_population
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

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