python - 无法正确处理 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]
>>>
解决方案
您可以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))
推荐阅读
- angular - Angular document.addEventListener 监听外部点击
- r - R plot没有根据文档添加绘图颜色?
- c - 为什么我会收到错误消息:'awk: read error (Is a directory)'
- php - Laravel 8 实现 PHP 的 DOM XML 函数输出 XML
- javascript - 更改 Material UI 中的步骤时,垂直步进器应滚动到顶部反应
- css - 第二行和后续行没有在网格中指定全高
- python - 在一张图中绘制更多垂直密度图
- python-3.x - Python matplotlib 无法在椭圆曲线 y^2+x^3+x^2=0 上绘制 Acnode(孤立点)
- node.js - expressjs 返回具有相同标签的项目列表
- c# - C# Interop.Excel 找不到 dll