Multiplying values from two different dictionaries together in Python

前端 未结 3 706
天涯浪人
天涯浪人 2021-01-12 16:43

I have two separate dictionaries with keys and values that I would like to multiply together. The values should be multiplied just by the keys that they have.

i.e.

相关标签:
3条回答
  • 2021-01-12 17:33

    You can use a dict comprehension:

    >>> {k : v * dict2[k] for k, v in dict1.items() if k in dict2}
    {'a': 15, 'b': 20}
    

    Or, in pre-2.7 Python, the dict constructor in combination with a generator expression:

    >>> dict((k, v * dict2[k]) for k, v in dict1.items() if k in dict2)
    {'a': 15, 'b': 20}
    
    0 讨论(0)
  • 2021-01-12 17:34

    From my telephone, so bit hard to type code. This should do the trick:

    for key, value in dict1.iteritems():
        if key in dict2:
             dict3[key] = int(dict1[key]) * int(dict2[key])
    
    0 讨论(0)
  • 2021-01-12 17:36
    dict1 = {'a': 1, 'b': 2, 'c': 3}
    dict2 = {'a': 15, 'b': 10, 'd': 17}
    
    def dict_mul(d1, d2):
        d3 = dict()
        for k in d1:
            if k in d2:
                d3[k] = d1[k] * d2[k]
        return d3
    
    print dict_mul(dict1, dict2)
    
    0 讨论(0)
提交回复
热议问题