【问题标题】:Looping through list of dictionary遍历字典列表
【发布时间】:2019-11-29 19:55:40
【问题描述】:

背景

我有一个字典列表,如下所示:

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'}]

目标

使用if 语句或for 语句到print 除'type': 'DATE 之外的所有内容

示例

我希望它看起来像这样:

for dic in list_of_dic: 

    #skip  'DATE' and corresponding 'text'
    if edit["type"] == 'DATE':
        edit["text"] = skip this

    else:
        print everything else that is not 'type':'DATE' and corresponding 'text': '1/1/2000'

期望的输出

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': 'T10','type': 'DOCTOR','start': 692,'end': 701,'text': 'Joe'}]

问题

如何使用循环实现我想要的输出?

【问题讨论】:

  • print([i for i in list_of_dic if i["type"] != "DATE"]) ?
  • @Rakesh 你是对的,但是 OP 是要求提供新列表还是要打印相关词典??
  • @Adi219..以上只是一个例子。将列表推导式存储在变量中并不难。

标签: python-3.x string list loops dictionary


【解决方案1】:

试试这个:

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'}]

newList = []
for dictionary in list_of_dic:
    if dictionary['type'] != 'DATE':
        newList.append(dictionary)

【讨论】:

    【解决方案2】:

    使用列表理解:

    In [1]: 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'}]
    
    In [2]: out = [i for i in list_of_dic if i['type'] != 'DATE']
    
    In [3]: out
    Out[3]:
    [{'id': 'T1',
      'type': 'LOCATION-OTHER',
      'start': 142,
      'end': 148,
      'text': 'California'},
     {'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
     {'id': 'T10', 'type': 'DOCTOR', 'start': 692, 'end': 701, 'text': 'Joe'}]
    

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      相关资源
      最近更新 更多