abdul rehman
abdul rehman

Reputation: 37

Optimizing the Nested dictionary in python problem

If one receiver has the most in each category you have to return his name. If there is no receiver with the most values in all categories you should return 'None of them'.

receivers = ({'abdul': {'a': 1800, 'b': 18, 'c': 117},
              'ahmed' :  {'a': 1700, 'b': 17, 'c': 116},
              'rehman' : {'a': 1750,'b': 16, 'c': 113}})
     
def triple_crown(receivers):
aa= [j['a'] for i,j in l.items()]
bb= [j['b'] for i,j in l.items()]
cc= [j['c'] for i,j in l.items()]
p = ['abdul', 'ahmed', 'rehman']
for i,j in enumerate(list(zip(aa,bb,cc))):
    x,y,z=j
    if x==max(aa) and aa.count(x)==1:
        if y==max(bb) and bb.count(y)==1:
            if z==max(cc) and cc.count(z)==1:
                return p[i]
else:
    return 'None of them'

the output should be 'abdul' since he has more a,b and c value than his counterparts

I defined the function this way but i guess there should be a better way to do this as this very bad solution

Upvotes: 0

Views: 86

Answers (1)

user7864386
user7864386

Reputation:

Here's one approach:

First, traverse receivers and the inner dicts to create a dictionary max_dct from the max values across all inner dicts

Then, check if the max_dct exists in receivers, if it does, find the key it corresponds to, if not print "None"

max_dct = {}
for name, dct in receivers.items():
    for k,v in dct.items():
        max_dct[k] = max_dct[k] if k in max_dct and max_dct[k] > v else v

out = None
for name, dct in receivers.items():
    common_vals = set(max_dct.values()) & set(dct.values())
    if common_vals:
        if len(common_vals) == len(max_dct):
            out = name
        break
        
out = out if out is not None else 'None of them'
print(out)

Output:

abdul

Upvotes: 1

Related Questions