[英]Iterating over a dictionary in Python
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]
. 我想避免在没有
[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!
任何帮助将不胜感激!
It's better to change your App
class, but if you can't change it, then: 最好更改您的
App
类,但是如果您不能更改它,则:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.