首页 > 解决方案 > Python - Merge two dictionaries into a single list (By Keys)

问题描述

I have:

market = {
       "APPL" : 2.33 },
        "IBM" : 3.44 },
        "AMZN" : 5.33 }
}

portfolio = {
        "APPL" : 0.20,
        "IBM" : 0.05
}

I want to merge the above dictionaries into a single list, that has the following structure. It uses common keys to do the multiplication:

index 0:  Multiplication of 2.33 and 0.20
index 1:  Multiplication of 3.44 and 0.05

Any ideas?

标签: python

解决方案


You could iterate through the items of portfolio like this:

[value * market[key] for key, value in portfolio.items()]

or, if you wanted to keep the keys:

{key: value * market[key] for key, value in portfolio.items()}

Edit: I missed that you wanted a list, not a dict


推荐阅读