1

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!

6
  • 3
    dictionary is supposed to be random access. You wont be able to extract elements from a dict using index. So there is just the question of extracting, not sorting Commented Nov 22, 2017 at 6:42
  • @VivekKalyanarangan What about sorted(mydict.iterkeys()) Commented Nov 22, 2017 at 6:47
  • What's in your files? Are you reading them and creating dicts for each line? There's probably a better approach, but it's hard to say without knowing what's in the files and what the ultimate goal is. Commented Nov 22, 2017 at 6:47
  • @JesseBarnett I think it would be more like sorted(d.values(), key=lambda value: -len(value)) Commented Nov 22, 2017 at 6:48
  • @Blurp that will be far more useful to OP, I was just responding to the comment about sorting dict. Commented Nov 22, 2017 at 6:54

3 Answers 3

2

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])
Sign up to request clarification or add additional context in comments.

6 Comments

You can do sorted(..., reverse=True) to avoid list(reversed(...))
@Blurp thanx i didn't know that i will update my code
Well, are you sure dict(list) will work, I thought we need to zip the list because this does not work in console.
@NanduKalidindi go ahead and try its tested ,it will work because we can convert list of tuples having key-value pair in dict we can't convert directly list of tuples which are not in key-value pair to dict
@NanduKalidindi you can see the above code its already done in ipython
|
1

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.

2 Comments

my_d.iteritems() works in Python 2.X. my_d.items() to be used in Python 3.X
How to get the top two elements of the x? [0:2] doesn't work :)
0
  • 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

2 Comments

Yeah not a Python expert yet, but since OP is more interested in the complexity I thought a breakdown would help him to easily judge the answer.
atleast you should have written your answer in pythonic way in last its not for the people who ask question from us but also for the benefit for the other people who are watching your code right

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.