如何从文件中向现有的空值键字典添加值?

How to add values to an existing empty value key dictionary from a file?

我有以下代码来创建空字典:

empty_dict = dict.fromkeys(['apple','ball'])
empty_dict = {'apple': None, 'ball': None}

我有这本空字典。

现在我想添加来自 value.txt 的值,其中包含以下内容:

value.txt
1
2

我希望生成的字典为:

{
"apple" : 1,
"ball" : 2
}

我不确定如何只更新字典中的值。

你真的不需要先做 dict——它不方便正确的顺序。您可以只 zip() 键和文件行并将其传递给字典构造函数,如:

keys = ['apple','ball']

with open(path, 'r') as file:
    d = dict(zip(keys, map(str.strip, file)))

print(d)
# {'apple': '1', 'ball': '2'}

这使用 strip() 从文件的行中删除 \n 个字符。

不清楚如果你的行数多于键数会发生什么,但上面会忽略它们。