SFC
SFC

Reputation: 793

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

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?

Upvotes: 0

Views: 41

Answers (2)

Osman Mamun
Osman Mamun

Reputation: 2882

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

Upvotes: 1

Adi219
Adi219

Reputation: 4814

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)

Upvotes: 1

Related Questions