简体   繁体   English

Python - 将两个词典合并为一个列表(按键)

[英]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? 有任何想法吗?

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 编辑:我错过了你想要一个清单,而不是一个字典

您可以使用列表推导来迭代portfolio的键并输出相应值的产品:

[market[k] * v for k, v in portfolio.items()]

You could use a list comprehension: 你可以使用列表理解:

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

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

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

# [0.466, 0.17200000000000001]

Note, though, that dicts are only ordered since Python 3.6, so the order of the values in the list are only guaranteed to match the order of the items in the portfolio dict with these versions. 但请注意,dicts仅在Python 3.6之后进行排序,因此列表中值的顺序仅保证与产品portfolio中的项目顺序与这些版本相匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM