首页 > 解决方案 > 无法正确处理 dict

问题描述

我有得到列表的 dict,我想要的是在一行中显示列表元素。

我的听写

data = {'id':[1,2], 'name':['foo','bar'], 'type':['x','y']}

预期产出

   name is foo and id is 1
   name is bar and id is 2

我的代码

>>> data = {'id':[1,2], 'name':['foo','bar'], 'type':['x','y']}
>>> for key, value in data.items():
...     print(value)
... 
['foo', 'bar']
['x', 'y']
[1, 2]
>>> 

标签: pythonpython-3.x

解决方案


您可以zip()用作:

for name, idx in zip(data['name'], data['id']):
    print(f"name is {name} and id is {idx}")

如果您使用format()低于 3.6 的 python 版本,请使用:

for name, idx in zip(data['name'], data['id']):
    print("name is {0} and id is {1}".format(name, idx))

推荐阅读