0

I have a list of dictionary as below

my_list = [
{'Overall': 'PASS', 'subjects': 4, 'student_id': '90e263', 'data': {'Social': 71, 'Science': 55, 'Maths': 99, 'French': 79}}, 
{'Overall': 'FAIL', 'subjects': 4, 'student_id': '90e264', 'data': {'Social': 56, 'Science': 18, 'Maths': 61, 'French': 49}}
]

And I would like to add a key:value pair 'class': 'Third Standard' to all the dictionaries inside the list making the resultant list look like below -

my_list = [
{'Overall': 'PASS', 'subjects': 4, 'student_id': '90e263', 'data': {'Social': 71, 'Science': 55, 'Maths': 99, 'French': 79}, 'class': 'Third Standard'}, 
{'Overall': 'FAIL', 'subjects': 4, 'student_id': '90e264', 'data': {'Social': 56, 'Science': 18, 'Maths': 61, 'French': 49}, 'class': 'Third Standard'}
]

Note - This is a sample list with just two dictionaries but I've got 1000s of dictionaries in my actual list.

Can someone please help me with best way to update all dictionaries inside the list?

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
bunnylorr
  • 201
  • 1
  • 10
  • Iterate over the list, and set the `'class'` key of each item in the list to `'Third Standard'`. There is no _"best way"_ without more context – Pranav Hosangadi Jan 11 '23 at 22:51

2 Answers2

1

You can use the dictionary union operator with a list comprehension:

[entry | {"class": "Third Standard"} for entry in my_list]

Alternatively, if you'd like to modify the dictionaries in-place, you can use a simple for loop:

for entry in my_list:
    entry["class"] = "Third Standard"

This produces:

[
    {
        "Overall": "PASS",
        "subjects": 4,
        "student_id": "90e263",
        "data": {
            "Social": 71,
            "Science": 55,
            "Maths": 99,
            "French": 79
        },
        "class": "Third Standard"
    },
    {
        "Overall": "FAIL",
        "subjects": 4,
        "student_id": "90e264",
        "data": {
            "Social": 56,
            "Science": 18,
            "Maths": 61,
            "French": 49
        },
        "class": "Third Standard"
    }
]
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

Just iterate the list and add value to dictionary:

my_list = [
    {'Overall': 'PASS', 'subjects': 4, 'student_id': '90e263', 'data': {'Social': 71, 'Science': 55, 'Maths': 99, 'French': 79}}, 
    {'Overall': 'FAIL', 'subjects': 4, 'student_id': '90e264', 'data': {'Social': 56, 'Science': 18, 'Maths': 61, 'French': 49}}
]

for d in my_list:
    d["class"] = "Third Standard"
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    Please try looking for duplicates before adding an answer https://stackoverflow.com/questions/14071038/add-an-element-in-each-dictionary-of-a-list-list-comprehension Such basic questions are bound to have duplicates – Pranav Hosangadi Jan 11 '23 at 22:58