HackToTech

Hack To Technology

Pythonで辞書の配列から新たに辞書を作成する

pythonのreduceたまにどこにあるかよくわかんなくて迷う

from functools import reduce

ld = [{'Key': 'Key1', 'Value': 'Value1'}, {'Key': 'Key2', 'Value': 'Value2'}, {'Key': 'Key3', 'Value': 'Value3'}]
reduce(lambda acc, x: dict(acc, **{x['Key']: x['Value']}) , ld, {})
# {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}

ld2 = [{'Key1': 'Value1'}, {'Key2': 'Value2'}, {'Key3': 'Value3'}]
reduce(lambda acc, x: dict(acc, **x), ld2, {})
# {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}