Hi. I´m writing my first python program - a text adventure game. I want to have a list of possible things a dog could eat, what´s bad about them, 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]

There are actually around 40 foods I want to include. I know I can do this:

badfoods.append(dict(zip(keys,food1)))
badfoods.append(dict(zip(keys,food2)))

etc. Or, I could have written it another way for all 40 foods:

[{'Food':'alcohol', 'Problem':'alcohol poisoning', 'Imminent death':0},{'Food':'anti-freeze', 'Problem':'ethylene glycol', 'Imminent death':1}]

I prefer the first approach so I do not have to keep repeating the keys, but I don´t like how I have to write out append 40 times. I was wondering:

  1. Are either of these approaches any good or is there a better way?
  2. I also tried the stuff below, but I think it doesn´t work because I´m creating a string and it doesn´t know it´s also a variable name:

    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()
    

Help?

Something like:

def main():
    badfoods = []
    keys = ['Food','Chemical','Imminent death']

    for food in [['alcohol', 'alcohol poisoning', 0],
                ['anti-freeze', 'ethylene glycol', 1],
                ['apple seeds', 'cyanogenic glycosides', 0],
                ['apricot seeds', 'cyanogenic glycosides', 0],
                ['avocado', 'persin', 0],
                ['baby food', 'onion powder', 0]]:
        badfoods.append(dict(zip(keys, food)))

    print badfoods

main()

?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.