I have created a dictionary called sol:
sol = {'Uranus': [2750, 3000, 2880], 'Mercury': [46, 70, 57], 'Earth': [147, 152, 150], 'Venus': [107, 109, 108], 'Mars': [205, 249, 228], 'Saturn': [1350, 1510, 1430], 'Jupiter': [741, 817, 779], 'Neptune': [4450, 4550, 4500], 'Pluto': [4440, 7380, 5910]}
And using a data file STATUS_FILE1:
Mars,True
Mercury,True
Neptune,True
Uranus,True
Earth,True
Venus,True
Pluto,False
Jupiter,True
Saturn,True
I have built the following list in the following to have the list run parallel with the dictionary in order.
def load_status(sol, status):
with open(STATUS_FILE1, "r") as s: #Opens data file
for line in s:
line = line.rstrip('\n')
if len(line) > 0:
k, v = line.split(',')
if k in sol:
sol[k].append(v) #Matches key with T/F value and adds to dictionary
status = [v[-1] for k, v in sol.items()] # Populates status list in correct order based on dict
for k, v in sol.items(): # Removes unneeded T/F from dictionary
v.pop()
booleans = [] # Converts string to boolean terms
for v in status:
if v == "True":
booleans.append(True)
else:
booleans.append(False)
status = booleans # Final list converted
print(status)
So this prints exactly what I want:
[True, True, True, True, True, True, True, True, False]
However, even if I use a return function, in the main() function the status[] list is empty. Even if I remove the v.pop and boolean conversion it still prints a blank list. I've moved it around, and I am stumped and frustrated due to completing the function just to have it fail. Any ideas would be appreciated.
As requested, the status will then be used in the following format:
print("The list of all planets is:", planets_list(sol, status))
This function uses the status as shown here:
idx = 0
for planet in planets:
if stat[idx]:
pl.append(planet)
idx += 1
Inside your
load_statusyou're discarding thestatusparameter, building a new list, and then not returning it to the caller. Since you ignore thestatusthat the caller passed you, it shouldn't be a parameter in the first place, and should instead be the return value that you give back to the caller (i.e. it should be the output, rather than the input, of the function).At the beginning of
load_status, change:to:
Then at the end of
load_status, change:to:
Then in your
main()function, change:to:
Now you still get the list printed out, but it's also available as a variable called
statusin the body ofmain().