遍历字典列表时如何获取前一个字典的modificationDate值
问题
我有如下字典列表:
history_changes = [ {'userName': 'recg', 'modificationDate': '2022-07-14T04:01:39+00:00', 'changeComment': 'more details about L2'}, {'userName': 'artf', 'modificationDate': '2022-07-15T04:01:39+00:00', 'changeComment': 'more details about L1'}, {'userName': 'zrt', 'modificationDate': '2022-07-16T04:01:39+00:00', 'changeComment': 'more details about L3'}]
我正在遍历该列表并尝试将数据插入数据库,当前代码如下:
for record in history_changes[1:]: comment = record['changeComment'] to_time = record['modificationDate']
我还需要获取start_time信息,即前一个字典中的modificationDate值。预期输出如下:
comment = 'more details about L1' start_time = '2022-07-14T04:01:39+00:00' to_time = '2022-07-15T04:01:39+00:00' comment = 'more details about L3' start_time = '2022-07-15T04:01:39+00:00' to_time = '2022-07-16T04:01:39+00:00'
请问遍历该列表时,如何获取前一个字典中的modificationDate值?
解决方案
方法1:通过索引遍历
直接遍历列表的索引(从1开始),利用索引差i-1获取前一个元素:
for i in range(1, len(history_changes)): current_record = history_changes[i] prev_record = history_changes[i-1] comment = current_record['changeComment'] start_time = prev_record['modificationDate'] to_time = current_record['modificationDate'] # 此处执行插入数据库的逻辑 print(f" comment = '{comment}'") print(f" start_time = '{start_time}'") print(f" to_time = '{to_time}'\n")
方法2:用zip配对前后元素
将原列表与原列表从第二个元素开始的切片配对,循环时可同时拿到前一个和当前元素,写法更简洁:
for prev_record, current_record in zip(history_changes, history_changes[1:]): comment = current_record['changeComment'] start_time = prev_record['modificationDate'] to_time = current_record['modificationDate'] # 此处执行插入数据库的逻辑 print(f" comment = '{comment}'") print(f" start_time = '{start_time}'") print(f" to_time = '{to_time}'\n")
两种方法都能满足需求,zip的方式更符合Pythonic风格,适合这类连续元素配对的场景。
内容的提问来源于stack exchange,提问作者coLby
相关产品推荐
相关产品推荐

