Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

Cannot divide two dictionaries in Python

I'm trying to divide a dictionary by another dictionary and I cannot find a solution online that works.

Code:

def getRatio(price_a, price_b):
    """ Get ratio of price_a and price_b """
    """ ------------- Update this function ------------- """
    """ Also create some unit tests for this function in client_test.py """
    if (price_b == 0):
        # avoid zero division error
        return

    return price_a / price_b

Output:

line 51, in getRatio
    return price_a / price_b
TypeError: unsupported operand type(s) for /: 'dict' and 'dict'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following code returns the ratios as a dictionary with A's keys. If this is not the desired behavior, please clarify.

The solution using dictionary comprehension:

a = {'A':1, 'B':5, 'D':6}
b = {'X':4, 'Y':8, 'Z':4}

{key:val_a/val_b for ((key, val_a), val_b) in zip(a.items(), b.values())}

# Output:
# {'A': 0.25, 'B': 0.625, 'D': 1.5}

If you want the ratios as an array without the keys, you can use list comprehension:

[val_a/val_b for (val_a, val_b) in zip(a.values(), b.values())]
# Output for example above
# [0.25, 0.625, 1.5]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...