I am trying to loop over array of dicts and create a new dict using a for loop:
data
JavaScript
x
14
14
1
src_roles = [{
2
"rol1": {
3
"identity": 169309,
4
"labels": [
5
"Role"
6
],
7
"properties": {
8
"cs_id": "AB778C",
9
"name": "CMO",
10
"critical_role": True
11
}
12
}
13
}]
14
for loop:
JavaScript
1
4
1
src_roles_dict = {
2
role['rol1']['cs_id']: role for role in src_roles if role['rol1'].get('cs_id')
3
}
4
And when I print src_roles_dict
, I get an empty dict {}
Is there something I am missing? Sorry, coming from golang background.
Advertisement
Answer
JavaScript
1
21
21
1
src_roles = [{
2
"rol1": {
3
"identity": 169309,
4
"labels": [
5
"Role"
6
],
7
"properties": {
8
"cs_id": "AB778C",
9
"name": "CMO",
10
"critical_role": True
11
}
12
}
13
}]
14
15
src_roles_dict = {
16
role['rol1']["properties"]['cs_id']: role for role in src_roles if role["rol1"]["properties"].get("cs_id")
17
}
18
19
print(src_roles_dict)
20
21
Output
JavaScript
1
2
1
{'AB778C': {'rol1': {'identity': 169309, 'labels': ['Role'], 'properties': {'cs_id': 'AB778C', 'name': 'CMO', 'critical_role': True}}}}
2