J87
J87

Reputation: 179

How to compare same keys values from two different dict with percentage

Trying to compare same keys values from two different dict, If second dict values are bigger by 50% than first dict values then output should show different keys values only.

Example:
first={'a': '1000', 'b': '2000', 'c': '2400'}
second={'a': '1000', 'b': '3000', 'c': '5000'}
new dict output should be {'c': '5000'} # c is 50% bigger from first dict value

how to do this comparison

below code shows if bigger only without percentage , how to get if second values are bigger by 50%

print(dict((k, second[k])for k in second if second[k] > first[k]))

Upvotes: 2

Views: 70

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49862

You can do that comparison by converting your strings to int(), and then compare one with the other times 1.5 inside a dict comprehension like:

Code:

{k: v for k, v in second.items() if int(v) > int(first[k]) * 1.5}

Test Code:

first={'a': '1000', 'b': '2000', 'c': '2400'}
second={'a': '1000', 'b': '3000', 'c': '5000'}
desired = {'c': '5000'} # c is 50% bigger from first dict value

print({k: v for k, v in second.items() if int(v) > int(first[k]) * 1.5})

Results:

{'c': '5000'}

Upvotes: 1

Related Questions