0

I need to create a list of dictionary values, sorted based on whether or not the value is empty, my attempt gets the desired output but has to iterate twice over the dictionary, I was wondering if there was a way to do this only iterating once? My actual dictionary contains like 50,000 values and just iterating once would save some time when doing it repeatedly

d = {'id1':[],
     'id2':[1],
     'id3':[1]}
l = [v for v in d.values() if v]+[v for v in d.values() if not v]
print (l)

this is my desired output:

[[1], [1], []]

2 Answers 2

3

You can sort with respect to length:

l = sorted(d.values(), key=len, reverse=True)
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest SortedContainers : Fast, pure-Python implementation of SortedList, SortedDict, and SortedSet types.

from sortedcontainers import SortedList
d = {'id1':[],
     'id2':[1],
     'id3':[1]}

res=SortedList(d.values())

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.