I was wanting to append strings from a text file (line by line) and then set these strings equal to a None value. Is there a way to default each of these Values to None?
I.e. Text File:
Hello
World
Dictionary:
{"Hello":None, "World":None}
I was wanting to append strings from a text file (line by line) and then set these strings equal to a None value. Is there a way to default each of these Values to None?
I.e. Text File:
Hello
World
Dictionary:
{"Hello":None, "World":None}
Not sure why you'd want a dictionary of None
s.... But here you go
Dictionary={}
with open(FILE, "rt") as f:
for line in f.readlines():
Dictionary[line.strip()]=None
@KJTHoward's answer works well. If you want, there's also a built-in method to do just that called dict.fromkeys()
. See that answer.
with open("path/to/file", "r") as f:
my_dict = dict.fromkeys([line.strip() for line in f.readlines()])
Or a clean dict comprehension way:
with open("path/to/file", "r") as f:
my_dict = {key: None for key in [line.strip() for line in f.readlines()]}