answer = {} # initialize an empty dict
with open('path/to/file') as infile: # open the file for reading. Opening returns a "file" object, which we will call "infile"
# iterate over the lines of the file ("for each line in the file")
for line in infile:
# "line" is a python string. Look up the documentation for str.strip().
# It trims away the leading and trailing whitespaces
line = line.strip()
# if the line starts with "Object"
if line.startswith('Object'):
# we want the thing after the ":"
# so that we can use it as a key in "answer" later on
obj = line.partition(":")[-1].strip()
# if the line does not start with "Object"
# but the line starts with "Orbital Radius"
elif line.startswith('Orbital Radius'):
# get the thing after the ":".
# This is the orbital radius of the planetary body.
# We want to store that as an integer. So let's call int() on it
rad = int(line.partition(":")[-1].strip())
# now, add the orbital radius as the value of the planetary body in "answer"
answer[obj] = rad
Hope this helps
Sometimes, if you have a number in decimal notation ("floating point numbers" in python-speak) in your file (3.14
, etc), calling int
on it will fail. In this case, use float()
instead of int()