简体   繁体   中英

Select keys with same length of value which is highest count list in dictionary

I have a sorted defaultdict like:

k = {'a':[3,4,5] , 'x':[5,4,11] , 'c':[1,3,4] , 'l': [2,3], 'h':[1]}

What I want is to get only keys with highest or higesht equal length in value.

Expected output:

{'a':[3,4,5] , 'x':[5,4,11] , 'c':[1,3,4]} or [a,b,c]

I have used numpy to get true values in an array and then extract it my code:

z = np.array(arr)     #arr variable has the size of lists i.e arr = [3,3,3,2,1]
    p = len(z[z == z[0]])    #To Check how many highest count is SAME and store the count in p variable
    print(z >= z[0])
    print(list(k)[0:p])

Output :-

True True True False False

[a,x,c]

So my question is, is there any way to do this without using numpy ?

One way is to calculate the maximum length, then use a dictionary comprehension.

d = {'a':[3,4,5] , 'x':[5,4,11] , 'c':[1,3,4] , 'l': [2,3], 'h':[1]}

max_len = max(map(len, d.values()))

res = {k: v for k, v in d.items() if len(v) == max_len}

print(res)

{'a': [3, 4, 5], 'x': [5, 4, 11], 'c': [1, 3, 4]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM