I am practicing how to become better at working with dictionaries in python. For the sake of practice I'm trying to write a program that reads information about people from a file, and then store the information in a nested dictionary like this {'key':value, {gender:male_or_female} }
The data file looks like
Bob, 35, Male
George, 53, Male
Karen, 67, Female
Jamie, 20, Female
Aisha, 12, Female
Maria, 50, Female
Rolf, 16, Male
Ali, 90, Male
The code I have written so far goes like
def extract_person_data(filename):
dicti = {}
infile = open(filename)
for line in infile:
words = line.split(",")
name = words[0]
age = words[1]
gender = words[2]
dicti[name] = age
dicti["Gender"] = gender
infile.close()
return dicti
print(extract_person_data("people.txt"))
The program outputs:
{'Bob': ' 35', 'Gender': ' Male', 'George': ' 53', 'Karen': ' 67', 'Jamie': ' 20', (...)}
Note that 'Gender': 'Male
only appears in the first list item. In other words, it returns kind of what I want, but not quite.
My questions is
How can assign a nested dictionary into each one of the main list items like {'key':value, {gender:male_or_female} }
?
I hope there is someone who is kind enough to provide a rookie who is eager to learn with a solution and some explanation.
All help is massively appreciated.
CodePudding user response:
What I think you really want is to create a list
of elements, each of which is a dict
with key value pairs of the data of each person:
def extract_person_data(filename):
result = []
infile = open(filename)
for line in infile:
words = line.split(",")
name = words[0]
age = words[1]
gender = words[2]
dicti = {'name':name, 'age':age, 'Gender': gender}
result.append(dicti)
infile.close()
return result
print(extract_person_data("people.txt"))
There are a few improvements I would suggest.
Splitting the line using ", "
to remove the leading space. Also .strip()
the line to remove the trailing linefeed.
Then it is better to use with open(...
to ensure the file is always closed.
def extract_person_data(filename):
result = []
with open(filename) as infile:
for line in infile:
words = line.strip().split(", ")
name = words[0]
age = words[1]
gender = words[2]
dicti = {'name':name, 'age':age, 'Gender': gender}
result.append(dicti)
return result