user8871463
user8871463

Reputation:

How to sort dictionary with lists in python

I have a dictionary as follows.

my_d={"0":["code_5", "code_4", "code_10"],
 "1":["code_1", "code_2", "code_3", "code_11"], 
"2": ["code_7", "code_8"], "3": ["code_9"]}

I want to sort the dictionary by considering the number of elements in its list. That is "1": ["code_1", "code_2", "code_3"] has 3 elements, so should be in the first place of the dictionary. Hence my output should be as follows.

my_d = {"1":["code_1", "code_2", "code_3", "code_11"],
 "0":["code_5", "code_4", "code_10"],
 "2": ["code_7", "code_8"], "3": ["code_9"]}

Now I want to get only the first 2 keys of the dictionary. So, my final output should look as follows.

my_d={"1": ["code_1", "code_2", "code_3", "code_11"],
 "0":["code_5", "code_4", "code_10"]}

My files are very large. So I want a quick and efficient way of doing this in python. Please help me!

Upvotes: 1

Views: 111

Answers (3)

Argus Malware
Argus Malware

Reputation: 787

you can try this way

a =list(sorted(my_d.items(),key = lambda x:len(x[1]),reverse = True)[0:2]
print a
Out[94]: 
    [('1', ['code_1', 'code_2', 'code_3', 'code_11']),
     ('0', ['code_5', 'code_4', 'code_10'])]

 In [95]: dict(a)
 Out[95]: 
    {'0': ['code_5', 'code_4', 'code_10'],
     '1': ['code_1', 'code_2', 'code_3', 'code_11']}

in one word your answer is

a =dict(list(sorted(my_d.items(),key = lambda x:len(x[1]),reverse = True))[0:2])

Upvotes: 2

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

  • Converting dictionary to array
  • Sorting the array based on the second index
  • Slicing the last two elements
  • Converting array back to dictionary

The below solution might be a little expensive for your use case. It's basically

my_d={"0":["code_5", "code_4", "code_10"], "1":["code_1", "code_2", "code_3", "code_11"], 
"2": ["code_7", "code_8"], "3": ["code_9"]}

# Convert to array
k = list(my_d.items())

# Ascending sort
k.sort(key=lambda x: len(x[1]))

# Slice last two elements
k = k[-2:]

# Convert back to dictionary
dict = {}
for i in range(len(k)):
     dict[k[i][0]] = k[i][1]

dict will contain the desired output

Upvotes: 0

nehem
nehem

Reputation: 13652

As pointed out in the comments, the order of the keys in a dict is not guaranteed, if you would need you must use OrdredDict from Python's collections

from collections import OrderedDict
x = OrderedDict(sorted(my_d.iteritems(), key=lambda x:len(x[1]), reverse=True))

That way the new dict x will preserve the order you are looking for.

Upvotes: 1

Related Questions