获取列表中每个键的字典值
假设我有一个列表:
a = ['apple', 'carrot']
还有一个字典:
d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}
我该如何用这个列表 a 作为关键字去查找字典 d 呢?我想把结果写入一个用逗号分隔的文本文件,格式如下:
apple, carrot
2, 44
4, 33
把列表 a 从 a = ['apple', 'orange'] 改成 a = ['apple', 'carrot'] 了。
3 个回答
1
这个问题虽然很老了,但为了将来来看的人,我建议使用 列表推导式 来获取字典 d 中,列表 a 里的键 k 对应的值:
values = [ d[k] for k in a ]
8
a = ['apple', 'orange']
d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}
print ',\t'.join(a)
for row in zip(*(d[key] for key in a)):
print ',\t'.join(map(str, row))
输出:
apple, orange
2, 345
4, 667
3
我知道其他人可能做得更快,他们的解决方案也差不多,但这是我的看法(你可以接受也可以不接受):
a = ['apple', 'orange']
d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}
fo = open('test.csv','w')
fo.write(',\t'.join(a)+'\n')
for y in xrange(len(d[a[0]])):
fo.write(',\t'.join([str(d[i][y]) for i in a])+'\n')
fo.close()
这段代码会生成一个名为 test.csv 的文件:
apple, orange
2, 345
4, 667