从词典列表创建新列表 [英] Creating a new list from list of dictionaries

查看:67
本文介绍了从词典列表创建新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

以下代码可为日期添加2天(例如,1/1/2000变为1/3/2000,并取自

The following code works for adding 2 days to a date (e.g. 1/1/2000 becomes 1/3/2000 and is taken from Altering date in list of dictionary

import datetime

list_of_dic = [{'id': 'T1','type': 'LOCATION-OTHER','start': 142,'end': 148,'text': 'California'},
 {'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
 {'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '1/1/2000'},
 {'id': 'T10','type': 'DOCTOR','start': 692,'end': 701,'text': 'Joe'},
 {'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '5/1/2000'}]

for i in list_of_dic:           #Iterate list
    if i["type"] == 'DATE':     #Check 'type'
        i["text"] = (datetime.datetime.strptime(i["text"], "%m/%d/%Y") + datetime.timedelta(days=2)).strftime("%m/%d/%Y")   #Increment days. 

print(list_of_dic)

输出

[{'id': 'T1', 'type': 'LOCATION-OTHER', 'start': 142, 'end': 148, 'text': 'California'}, 
   {'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'}, 
   {'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '01/03/2000'}, 
  {'id': 'T10', 'type': 'DOCTOR', 'start': 692, 'end': 701, 'text': 'Joe'}, 
 {'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '05/03/2000'}]

问题

如果要将print(list_of_dic)的输出保存在名为new_list_of_dic的新列表中,代码将如何更改?

How would the code change if one wanted to save the output from print(list_of_dic) in a new list called new_list_of_dic?

推荐答案

只需使用copy?

new_list_of_dic = list_of_dic.copy()

或者您是否想要字符串?

Or if you want the string?

new_list_of_dic = str(list_of_dic)

这篇关于从词典列表创建新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆