首页 > 解决方案 > 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

我现在需要在一个循环中,在同一个循环迭代中提取一个内容值和一个时间值。任何建议表示赞赏。

标签: pythonloopsflask

解决方案


我认为你走错路了。字典未排序,因此您拥有的输出根本不固定。如果有更多数据进入输出,则可能到处都是。

我建议以不同的方式创建字典。

我会做一个这样的元组列表:

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"]


推荐阅读