python - Python字典,一次迭代提取两个值
问题描述
我有一本包含两个“重复”值的字典,一个命名为内容,第二个命名为时间。此 dict 是使用 for 循环创建的:
loopindex = 1
thisdict = {}
for u in Comment.select():
stringloop = str(loopindex)
if u.commentId == tempid:
print('match')
thisdict.update({"content" + stringloop: u.commentContent})
thisdict.update({"time" + stringloop: u.timestamp})
loopindex += 1
在 for 循环(键、值)中使用 print 时,我最终会得到以下输出:
content1 This is a comment attempt
time1 2020-01-04 11:28:05.507961
content2 This is a comment attempt
time2 2020-01-04 11:33:05.108815
content3 This is a comment attempt
time3 2020-01-04 11:33:33.153281
content4 This is a comment attempt
time4 2020-01-04 11:34:37.880837
我现在需要在一个循环中,在同一个循环迭代中提取一个内容值和一个时间值。任何建议表示赞赏。
解决方案
我认为你走错路了。字典未排序,因此您拥有的输出根本不固定。如果有更多数据进入输出,则可能到处都是。
我建议以不同的方式创建字典。
我会做一个这样的元组列表:
output = []
for u in Comment.select():
if u.commentId == tempid:
print('match')
output.append((u.commentContent,u.timestamp))
output[i][0]
使用(内容)/ output[i][1]
(时间戳)访问它
或者如果你想使用字典而不是元组:
output.append({"content":u.commentContent,"timestamp":u.timestamp})
使用output[i]["content"]
/访问output[i]["timestamp"]
推荐阅读
- python - 如何告诉 slurm 缓存配置文件以进行多次提交
- docker - Docker容器,Centos,如何远程登录
- android-constraintlayout - layout_marginBottom 在 ConstraintLayout 中不起作用
- winjs - Typescript 2.8 中的 MSApp 等效项
- python - 熊猫不导入 excel 更改
- java - 在 Android 中,如何使用 VidEffects 的过滤器渲染视频
- c++ - 使输入二进制掩码适应 itk 网格生成器
- reactjs - 如何在 react-day-picker 中禁用日期数组?
- java - 从另一个列表中的对象填充列表
- java - JDBI 对象参数