How can I pick the value from list of dicts using python
Question:
I have a sample dict in the below format. I want to append more values in the headers
. How should I proceed?
data = {'heading': 'Sample Data', 'MetaData': [{'M1': {'headers': ['age', 'roll_no'], 'values': [15, 5]}}, {'M2': {'headers': [], 'values': []}}]}
To access, I can try something like – data['MetaData'][0]['headers'].append('class')
. It works this way but I want to access it via loop.
Answers:
You can append while looping like this,
data = {'heading': 'Sample Data', 'MetaData': [{'M1': {'headers': ['age', 'roll_no'], 'values': [15, 5]}}, {'M2': {'headers': [], 'values': []}}]}
for item in data['MetaData']:
for key, value in item.items():
headers = value['headers']
headers.append('class')
print(data)
I have a sample dict in the below format. I want to append more values in the headers
. How should I proceed?
data = {'heading': 'Sample Data', 'MetaData': [{'M1': {'headers': ['age', 'roll_no'], 'values': [15, 5]}}, {'M2': {'headers': [], 'values': []}}]}
To access, I can try something like – data['MetaData'][0]['headers'].append('class')
. It works this way but I want to access it via loop.
You can append while looping like this,
data = {'heading': 'Sample Data', 'MetaData': [{'M1': {'headers': ['age', 'roll_no'], 'values': [15, 5]}}, {'M2': {'headers': [], 'values': []}}]}
for item in data['MetaData']:
for key, value in item.items():
headers = value['headers']
headers.append('class')
print(data)