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.

Asked By: ninjacode

||

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)
Answered By: Always Sunny
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.