我有一个词典
x={'a':[1,'inr','in-gaap'],'b':[2,'','in-gaap'],'c':[3,'inr','']}
我打印的是这样的:
for key,values in x.iteritems():
print 'value:{0}ref:{1}pre:{2}'.format(x[key][0],x[key][1],x[key][2])
它的打印
value:1 ref:inr pre:in-gaap
value:2 ref: pre:in-gaap
value:3 ref:inr pre:
但我想要的输出是
value:1 ref:inr pre:in-gaap
value:2 pre:in-gaap
value:3 ref:inr
对于不存在的值,不应打印值。 我怎么能这样做?
答案 0 :(得分:4)
NAMES = 'value ref pre'.split()
for key, values in x.iteritems():
valstrs = ['%s:%s' % (name, value)
for name, value in zip(NAMES, values)
if value]
print ' '.join(valstrs)