1

There are several ways of creating a empty Dictionary in Python, for example:

#method 1
Alan = {}
#method 2
John = dict()

I want to create a number of Dictionaries to store personal information of a group of employees. A person's name will be used as a unique name in creating the empty Dictionary. Employees name are stored into a file (info.txt) and each line will only have one name.

#info.txt
Alan
John
Fiona
... x Repeat N times

The number of name or entry in the file is unpredictable, so I wish to have a flexible code to handle this type of scenario. My code will read every single line and try to create a empty Dictionary for each employee. However, my codes does not work because the Dictionary is not defined.

#read employee name from file
infoFile = open("info.txt","r")

#read every line and create Dictionary for each employee
for infoFileLine in infoFile:
    if not infoFileLine.strip():
        pass

    else:
        print("%s" %infoFileLine)
        designFileLine = dict()

#update employee personal info
Alan["Age"] = 36
Alan["Height"] = 180
John["Age"] = 36
John["Height"] = 180

I am new to Python, so what is wrong with my code above? Or is there any other better way of doing it? Thank you in advance.

SC Kong
  • 11
  • 2

1 Answers1

1

You should make a master dictionary that contains other dictionarys. Here is a brief example:

master = {}
names = ["Alan", "Peter"]

for n in names:
    master[n] = {}
print(master)

And the output is:

{'Alan': {}, 'Peter': {}}

Just change my names array for a file.readLines() method and it should work.

Angelo
  • 575
  • 3
  • 18