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

Viewed 213

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
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.

1 Answers

You don't really need to make the dict first — it makes it inconvenient to get the order correct. You can just zip() the keys and the file lines and pass it to the dictionary constructor like:

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.

It's not clear what should happen if you have more lines than keys, but the above will ignore them.

Related