I have list of dictionary in Python that i want to convert to another list after i split the value in the dictionary and take only first value after the split.
myList = [
{'name': 'CN=John,Li',
'type': 'Agent',
'isMember': False},
{'name': 'CN=Moses,Somewhere',
'type': 'Worker',
'isMember': True},
{'name': 'CN=David, Something',
'type': 'Agent',
'isMember': False}
]
required_fields = ['name', 'isMember']
I'm looking for desired output after splitting the values
myList = [
{'name': 'John',
'isMember': False},
{'name': 'Moses',
'isMember': True},
{'name': 'David',
'isMember': False}
]
Thank you in advance
CodePudding user response:
A small helper function to find the CN=...
part from the name, and a list comprehension to loop over myList
:
import re
def get_cn(name):
return re.search("CN=([^,] )", name).group(1)
my_list = [...]
new_list = [
{'name': get_cn(x['name']), 'isMember': x['isMember']}
for x
in my_list
]
print(new_list)
This outputs
[{'name': 'John', 'isMember': False}, {'name': 'Moses', 'isMember': True}, {'name': 'David', 'isMember': False}]
CodePudding user response:
This can be done in single liner -->
new_list = []
for i in range(len(myList)):
new_list.append({"name": re.search("CN=([^,] )", myList[i]['name']).group(1), \
"isMember":myList[i]['isMember']})
print(new_list)