0

I want to ask if we can filtered id that contain certain word only in python. I have these two json files. and I want to filter the id for only contain 'def###'?

a= [{'id':'abc23','name':'aa','age':'22',
     'data':{'read':'','speak':''},
     'responses':{'a':1,'b':2}},
     {'id':'abc25','name':'bb','age':'32',
      'data':{'read':'','speak':''},
      'responses':{'a':1,'b':2}},
    {'id':'abc60','name':'cc','age':'24',
     'data':{'read':'','speak':''},
     'responses':{'a':1,'b':2}},
    {'id':'def23','name':'aa','age':'22',
     'data':{'read':'','speak':''},
     'responses':{'a':1,'b':2}},
     {'id':'def25','name':'bb','age':'32',
      'data':{'read':'','speak':''},
      'responses':{'a':1,'b':2}},
    {'id':'def60','name':'cc','age':'24',
     'data':{'read':'','speak':''},
     'responses':{'a':1,'b':2}}]

The output should be: ID 'def' only will be exis.

[{'id':'def23','name':'aa','age':'22',
'data':{'read':'','speak':''},
'responses':{'a':1,'b':2}},
{'id':'def25','name':'bb','age':'32',
'data':{'read':'','speak':''},
'responses':{'a':1,'b':2}},
{'id':'def60','name':'cc','age':'24',
'data':{'read':'','speak':''},
'responses':{'a':1,'b':2}}]
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
FrahChan04
  • 178
  • 1
  • 11
  • Did you try? share your code please . – Guy Dec 30 '19 at 07:38
  • There is a very similar [question](https://stackoverflow.com/q/8653516/6682517) with several good answers. The most suitable answer for you is [this](https://stackoverflow.com/a/8653572/6682517) I think. – Sergey Shubin Dec 30 '19 at 08:47

2 Answers2

4

Use list comprehension with startswith:

a = [x for x in a if x['id'].startswith('def')

Or filter by first 3 characters:

a = [x for x in a if x['id'][:3] == 'def']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

If you want to check if the id key contains certain word for ex., def in its value, you can simply do the following:

for dict_row in a:
    if 'def' in dict_row['id']:
        print(dict_row)

Output

{'id': 'def23', 'name': 'aa', 'age': '22', 'data': {'read': '', 'speak': ''}, 'responses': {'a': 1, 'b': 2}}
{'id': 'def25', 'name': 'bb', 'age': '32', 'data': {'read': '', 'speak': ''}, 'responses': {'a': 1, 'b': 2}}
{'id': 'def60', 'name': 'cc', 'age': '24', 'data': {'read': '', 'speak': ''}, 'responses': {'a': 1, 'b': 2}}

You can use a list comprehension to have a list of your returned dictionaries:

def_list = [dict_row for dict_row in a if 'def' in dict_row['id']]
Somraj Chowdhury
  • 983
  • 1
  • 6
  • 14