How to extract a string from a list of sets

Question:

I want to extract some information form a list of sets . I know that I have to use python module re but i will be happy to have some help.
This is the list of sets:

[{'group_id': 'E1', 'subjects_affected': '4', 'subjects_at_risk': '104'},
 {'group_id': 'E2', 'subjects_affected': '7', 'subjects_at_risk': '105'}]

I want to extract information related to subjects_affected in each set. So I need to have :

['4','7']

Thank you,

Below is the current code:

import re

b=[{'group_id': 'E1', 'subjects_affected': '0', 'subjects_at_risk': '104'},
   {'group_id': 'E2', 'subjects_affected': '0', 'subjects_at_risk': '105'}]

re.findall(r'b{aff+b', b)
Asked By: Samir

||

Answers:

You don’t need re for this case:

c = [dic['subjects_affected'] for dic in b]
Answered By: Swifty

You can use a list comprehension:

>>> b=[{'group_id': 'E1', 'subjects_affected': '0', 'subjects_at_risk': '104'},
...  {'group_id': 'E2', 'subjects_affected': '0', 'subjects_at_risk': '105'}]
>>> [x['subjects_affected'] for x in b]
['0', '0']
Answered By: Fastnlight

You could use the map function to get all field values from the list of dicts:

b = [{'group_id': 'E1', 'subjects_affected': '4', 'subjects_at_risk': '104'},
     {'group_id': 'E2', 'subjects_affected': '7', 'subjects_at_risk': '105'}]
 
result = list(map(lambda elem: elem['subjects_affected'], b))

print(result)

Output:

['4', '7']
Answered By: Vasilis G.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.