Home > OS >  Multiply values of a dictionary
Multiply values of a dictionary

Time:05-29

I have two dictionaries, for example:

{"1":2,2:"5",3:"abcd",5:7}

{"1":10,2:5,3:"123",5:2.5}

And I need to create a new dictionary, where the keys are the same as in the first two, but the value is a product of values corresponding to the key if both values are numbers, the sum of values if they are strings. Otherwise exclude the key (and value) from the answer.

So the answer there will be: {"1":20,3:"abcd123",5:17.5}

Now my part of this code looks like this:

total = {key: price * key_values[key] for key, price in key_values.items()}

Is it somewhere near?

CodePudding user response:

Your attempt is is somewhat neat but (1) doesn't handle the types and (2) doesn't filter. I wouldn't use a dict comprehension here because filtering may be somewhat inconvenient. Just write this imperatively:

dict_a = {"1":2,2:"5",3:"abcd",5:7}
dict_b = {"1":10,2:5,3:"123",5:2.5}

dict_merged = {}
for key, value_a in dict_a.items():
    value_b = dict_b[key]
    if type(value_a) == str and type(value_b) == str:
        dict_merged[key] = value_a   value_b
    elif type(value_a) in (int, float) and type(value_a) in (int, float):
        dict_merged[key] = value_a * value_b

CodePudding user response:

Not recommended to use a dictionary comprehension if you are going to have conditions in there.

a = {"1":2,2:"5",3:"abcd",5:7}
b = {"1":10,2:5,3:"123",5:2.5}
c = {}
for key,value in a.items():
    b_value = b[key]
    if all(isinstance(x, (int, float)) for x in [value, b_value]):
        c[key] = value * b_value
    elif all(isinstance(x, str) for x in [value, b_value]):
        c[key] = value   b_value

print(c)

Ouptut:

{'1': 20, 3: 'abcd123', 5: 17.5}

Note: This is assuming that pre-condition you mentioned of both dicts to have same keys always is always met

  • Related