I´m writing a text adventure game as my first python program as suggested. I want to have a list of possible things a dog could eat, what´s bad about them, and how bad they are. So, I thought I´d do this:
badfoods = []
keys = ['Food','Problem','Imminent death']
food1 = ['alcohol', 'alcohol poisoning', 0]
food2 = ['anti-freeze', 'ethylene glycol', 1]
food3 = ['apple seeds', 'cyanogenic glycosides', 0]
badfoods.append(dict(zip(keys,food1)))
badfoods.append(dict(zip(keys,food2)))
badfoods.append(dict(zip(keys,food3)))
There are actually around 40 foods I want to include. I know I can also do this:
[{'Food':'alcohol', 'Problem':'alcohol poisoning', 'Imminent death':0},
{'Food':'anti-freeze', 'Problem':'ethylene glycol', 'Imminent death':1}
{'Food':'apple seeds, 'Problem':'cyanogenic glycosides', 'Imminent death':0}] ]
I also read this post on here about using YAML, which is appealing: What is the best way to implement nested dictionaries? but I still do not see how to avoid writing the keys a ton.
Plus, I am annoyed that I can´t figure out my original approach to avoiding writing the append 40 times, which is:
def poplist(listname, keynames, name):
listname.append(dict(zip(keynames,name)))
def main():
badfoods = []
keys = ['Food','Chemical','Imminent death']
food1 = ['alcohol', 'alcohol poisoning', 0]
food2 = ['anti-freeze', 'ethylene glycol', 1]
food3 = ['apple seeds', 'cyanogenic glycosides', 0]
food4 = ['apricot seeds', 'cyanogenic glycosides', 0]
food5 = ['avocado', 'persin', 0]
food6 = ['baby food', 'onion powder', 0]
for i in range(5):
name = 'food' + str(i+1)
poplist(badfoods, keys, name)
print badfoods
main()
I assume it doesn´t work because I am the for loop is creating a string and then feeding it to the function, and the function poplist doesn´t recognize it as a variable name. However, I don´t know if there´s a way to fix this or if I have to use YAML or write out the keys everytime. Any help is appreciated as I´m stumped!