Question

Write a Python function that takes as input a Python dictionary. As was done in the...

Write a Python function that takes as input a Python dictionary. As was done in the previous problem*, the function should first identify the value that occurs most frequently in the dictionary. However, instead of returning the value, the function should return a list of all the keys associated with that value. The function should not modify the dictionary in any way.

*code from previous problem

def most_frequent_value(d):
    most, most_count = '', 0
    new_d = {}
    for k, v in d.items():
        if v not in new_d:
            new_d[v] = 0
        new_d[v] += 1
    for k, v in new_d.items():
        if v > most_count:
            most_count = v
            most = k
    return most

print(most_frequent_value({
    "k1": "v1",
    "k2": "v2",
    "k3": "v1",
    "k4": "v3",
    "k5": "v1"
}))
0 0
Add a comment Improve this question Transcribed image text
Answer #1
def most_frequent_value(d):
    most, most_count = '', 0
    new_d = {}
    for k, v in d.items():
        if v not in new_d:
            new_d[v] = []
        new_d[v].append(k)
    for k, v in new_d.items():
        if len(v) > most_count:
            most_count = len(v)
            most = k
    return new_d[most]


print(most_frequent_value({
    "k1": "v1",
    "k2": "v2",
    "k3": "v1",
    "k4": "v3",
    "k5": "v1"
}))

Add a comment
Know the answer?
Add Answer to:
Write a Python function that takes as input a Python dictionary. As was done in the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT