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

标签 python dictionary key

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

关于python - 仅更改具有多个值的字典中键的一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43163719/

相关文章:

dictionary - 如何在groovy中的map变量中声明map并在jenkinsfile中调用它

python - 如何在 Python 中对嵌套列表的外部和内部子列表进行排序?

vim - 中止击键序列?

python - 在应用程序中包含 openssl

Python 代码在 CMD 中不起作用,但在 IDLE 中起作用?

c# - 将python模块转换成DLL文件

oracle - 外键是否总是引用另一个表中的唯一键?

python - 在 django 模板中格式化数字

python - 当键是元组时访问字典的键并检查元组的元素是否相等

从 2 个单独列表中的数据填充字典的 Python 过程