Home > database >  Python dict comprehension convert list of tuples of dictionaries and integers into list of dictionar
Python dict comprehension convert list of tuples of dictionaries and integers into list of dictionar

Time:06-03

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, z)
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}

CodePudding user response:

With python ≥3.9 you can use dictionary merging with the | operator:

out = [d|{'payroll': p} for d,p in zip(x,y)]

output:

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

CodePudding user response:

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