Tom Wragg
Tom Wragg

Reputation: 1

Need help creating a dictionary from a list and a function in Python

So i'm not sure how to explain it exactly but if you look at this code you may be able to help.

class tower:
    def __init__(self, name, namex, namey, x, y, width, height, nameimg):
        self.name = name
        self.namex = namex
        self.namey = namey
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.nameimg = nameimg

    def getname(self):
        return self.name
    def getnamex(self):
        return self.namex
    def getnamey(self):
        return self.namey
    def getx(self):
        return self.x
    def gety(self):
        return self.y
    def getwidth(self):
        return self.width
    def getheight(self):
        return self.height
    def getnameimg(self):
        return self.nameimg


background = tower("background", "backgroundx", "backgroundy", 0, 0, 1280, 720, backgroundImg)
ppsh = tower("ppsh", "ppshx", "ppshy", 1127, 140, 120, 40, ppshImg)
trenchgun = tower("trenchgun", "trenchgunx", "trenchguny", 1207, 140, 120, 27, trenchgunImg)
thompson = tower("thompson", "thompsonx", "thompsony", 1127, 120, 120, 39, thompsonImg)
colt = tower("colt", "coltx", "colty", 1, 1, 70, 46, coltImg)
mg = tower("mg", "mgx", "mgy", 1, 1, 135, 27, mgImg)

towers = [background, ppsh, trenchgun, thompson, colt, mg]

def game_loop():
    positions = {
        (background.getnamex()): (background.getx()),
        (background.getnamey()): (background.gety()),
        (ppsh.getnamex()): (ppsh.getx()),
        (ppsh.getnamey()): (ppsh.gety()),
        (trenchgun.getnamex()): (trenchgun.getx()),
        (trenchgun.getnamey()): (trenchgun.gety()),
        (thompson.getnamex()): (thompson.getx()), 
        (thompson.getnamey()): (thompson.gety()),
        (colt.getnamex()): (colt.getx()), 
        (colt.getnamey()): (colt.gety()),
        (mg.getnamex()): (mg.getx()), 
        (mg.getnamey()): (mg.gety()),
        }

if you look at the bottom section i want to make it so i don't have to write out a new line every time but take from the list above. Here is my attempt as an example.

towers = [background, ppsh, trenchgun, thompson, colt, mg]

def game_loop():
    for i in towers:
        positions = {
            (i.getnamex()): (i.getx()),
            (i.getnamey()): (i.gety()),
            }

if anyone can help it would be greatly appreciated, i've been stuck on this for a while now.

Upvotes: 0

Views: 41

Answers (1)

Nimish Bansal
Nimish Bansal

Reputation: 1759

You can define an empty dictionary and add the key value pair as required

def game_loop():
    global towers
    positions={}
    for i in towers:
        positions[i.getnamex()]= i.getx()
        positions[i.getnamey()]= i.gety()
    return positions

positions=game_loop()

Upvotes: 2

Related Questions