简体   繁体   English

遍历字典列表

[英]Looping through list of dictionary

Background 背景

I have a list a dictionaries as seen below: 我有一个字典列表,如下所示:

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

Goal 目标

Use an if statement or for statement to print everything except for 'type': 'DATE 使用if语句或for语句print'type': 'DATE以外的所有内容'type': 'DATE

Example

I would like for it to look something like this: 我希望它看起来像这样:

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'

Desired Output 期望的输出

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

Question

How do I achieve my desired output using loops? 如何使用循环实现所需的输出?

Try this: 尝试这个:

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)

Use list comprehension: 使用清单理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM