Interview Question

Data Engineer Interview

-

Meta

Given a dictionary, print the key for nth highest value present in the dict. If there are more than 1 record present for nth highest value then sort the key and print the first one (alphabetically). N can be higher than the number of elements in the dictionary.

AnswerAdd Tags

Interview Answers

9 Answers

2

''' x={'a':3,'d':1,'b':2, 'e':2} n=3 m = list(x.values()) m.sort(reverse=True) find = m[n-1] l=[] for key in sorted(x): if x[key]==find: l.append(key) return(l[0]) '''

Anonymous on

1

import random a={} n=6 for i in range(1,16): a[i]=random.randint(0,50) print(a) disvalues=sorted(list(set(a.values()))) print(disvalues) if n-1

bhaskar on

1

def nth(d, n): sorted_items = sorted(d.items(), key=lambda x: (x[1], x[0] ) ) print(sorted_items) return sorted_items[n] print(nth(x, 2))

Anonymous on

0

d = {'a':5 , 'b':4, 'c':3, 'd':3, 'e':1, 'f':3} def dictkey(d, n): x = sorted(((v,k) for k,v in d.items())) if n > len(d): return 0 else: nhigh = x[-n][0] li =[k for k,v in d.items() if v == nhigh] return li[0] print(dictkey(d,7))

Sheetal on

0

def max_n(ip_dict): max_val = max(ip_dict.values()) l = [] for i,j in r.items(): if j == max_val: l.append(i) l.sort() return l[0]

Anonymous on

0

def largest_value(dict,n): value= list(dict.values()) value.sort(reverse=True) largest_value = 0 largest_key = 0 for i,j in enumerate(value): if i+1==n: largest_value = j for m,n in dict.items(): if n==largest_value: largest_key=m return largest_key # Driver code dict = {'a': 1, 'b': 2, 'c': 100, 'd': 30} n = 2 result =largest_value(dict,n) print(result)

Anonymous on

0

def top_n(d, n): df=pd.DataFrame(d.items()) df.sort_values(by=[1, 0], ascending=False).loc(n, 0)

Anonymous on

0

def nth(dict, n): if n > len(dict): return None mydict = sorted(dict.items(), key=lambda x:x[1], reverse = True) li = [(v, k) for k, v in mydict] nth_val = li[n-1][0] res = [(v, k) for v, k in li if v == nth_val] d = sorted(res, key = lambda x:x[1]) d = [k for v, k in d] return d[0] mydict = {'a':3, 'b':3, 'c':2, 'd':2} res = nth(mydict, 3) print(res)

Jaren on

0

def myf(ip_dict, n): op_dict={} for k, v in ip_dict.items(): if v not in op_dict: op_dict[v] = k else: if k < op_dict[v]: op_dict[v] = k print(op_dict) op_list_val=[] for i in op_dict.keys(): op_list_val.append(i) op_list_val.sort(reverse=True) print(op_list_val) nth_highest_val = op_list_val[n-1] return op_dict[nth_highest_val]

Booya on

Add Answers or Comments

To comment on this, Sign In or Sign Up.