简体   繁体   English

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

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

I have the following code to create empty dictionary:我有以下代码来创建空字典:

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

I have this empty dictionary.我有这本空字典。

Now I want to add the values from value.txt which has the following content:现在我想从 value.txt 添加具有以下内容的值:

value.txt
1
2

I want the resultant dictionary to be as:我希望结果字典为:

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

I'm not sure how to update only the value from the dictionary.我不确定如何只更新字典中的值。

You don't really need to make the dict first — it makes it inconvenient to get the order correct.您实际上并不需要首先制作 dict - 它使正确的顺序变得不方便。 You can just zip() the keys and the file lines and pass it to the dictionary constructor like:您可以只zip()键和文件行并将其传递给字典构造函数,例如:

keys = ['apple','ball']

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

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

This uses strip() to remove the \n characters from the lines in the file.这使用strip()从文件中的行中删除\n字符。

It's not clear what should happen if you have more lines than keys, but the above will ignore them.如果行数多于键数,不清楚会发生什么,但上面会忽略它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM