添加键:Python3中字典列表中的值[重复]

j5fpnvbx  于 2023-01-14  发布在  Python
关注(0)|答案(2)|浏览(156)
    • 此问题在此处已有答案**:

Add an element in each dictionary of a list (list comprehension)(7个答案)
2天前关闭。
我有一张字典单如下

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}}
]

我想把一个键:值对'class': 'Third Standard'添加到列表中的所有字典中,使结果列表如下所示-

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'}
]

注意--这是一个只有两个字典的示例列表,但是在我的实际列表中有上千个字典。
有人能帮我更新列表中所有字典的最佳方法吗?

5n0oy7gb

5n0oy7gb1#

可以将字典联合运算符与列表解析一起使用:

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

或者,如果您想就地修改字典,可以使用一个简单的for循环:

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

这产生:

[
    {
        "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"
    }
]
oewdyzsn

oewdyzsn2#

只需迭代列表并向字典中添加值:

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"

相关问题