Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict comprehension convert list of tuples of dictionaries and integers into list of dictionaries

I have list of dictionaries and list of integers

x = [
    {
        "name": "tom",
        "job": "judge"
    },
    {
        "name":"bob",
        "job": "policeman"
    }
]
y = [1000, 2200]

I want to zip them and add y elements to dictionaries as "payroll": y_element The desired output would be:

[
    {
        "name": "tom",
        "job": "judge",
        "payroll": 1000
    },
    {
        "name":"bob",
        "job": "policeman",
        "payroll": 2200
    }
]

I actually achieved that by:

z = zip(x, y)
for i in z:
    i[0]["payroll"] = i[1]

z = [i[0] for i in z]

But I was wondering whether it could be done in dict comprehension in list comprehension. This is what I tried so far:

z = [{k: v, "value": o} for d, o in z for k, v in d.items()]

Obviously it is wrong because the output is:

{'name': 'bob', 'job': 'policeman', 'value': 2}
like image 735
M.wol Avatar asked Nov 01 '25 07:11

M.wol


1 Answers

You can merge the dict with the required data using ** here.

[{**d, 'payroll':i} for d, i in zip(x, y)]

# [{'name': 'tom', 'job': 'judge', 'payroll': 1000},
#  {'name': 'bob', 'job': 'policeman', 'payroll': 2200}]
like image 149
Ch3steR Avatar answered Nov 02 '25 20:11

Ch3steR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!