Question

I am trying to come up with a better solution but no luck so far. I have a dictionary:

dict = {"a":(1,2,3),"b":(4,5,6)}

I need to iterate it through a class:

class App(object):
    def __init__(self,x):
        self.x = x

    def key(self,key):
        print key

    def value1(self,value1):
        print value1

    def value2(self,value2):
        print value2

    def value3(self,value3):
        print value3

A solution I have so far is:

app = App(0)
while app.x < len(dict.keys()):
    app.key(dict.keys()[app.x])
    app.value1(dict.values()[app.x][0])
    app.value2(dict.values()[app.x][1])
    app.value3(dict.values()[app.x][2])   
    app.x +=1

I would like to avoid hard-coding, without [0],[1],[2]. If it is difficult to achieve with a dictionary, what data type should be use to get a desirable result? Any help would be highly appreciated!

Était-ce utile?

La solution

It's better to change your App class, but if you can't change it, then:

app = App(0)
funcs = [app.value1, app.value2, app.value3]
for i, (key, items) in enumerate(d.iteritems()):
    app.x = i
    app.key(key)
    for func, item in zip(funcs, items):
        func(item)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top