-1

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}
Samrat Sahoo
  • 565
  • 8
  • 17

2 Answers2

2

Not sure why you'd want a dictionary of Nones.... But here you go

Dictionary={}

with open(FILE, "rt") as f:
    for line in f.readlines():
        Dictionary[line.strip()]=None
KJTHoward
  • 806
  • 4
  • 16
0

@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()]}
arnaud
  • 3,293
  • 1
  • 10
  • 27