Reputation: 35
for example a is a dict, a = {1:2,2:3,3:4}
, and b= [3,1]
I want to sort a
to get a tuple list that if keys in a
is in b
, sort them in the order of b
, else put them in the end of the tuple list.
I do it like this :
sorted(a.items(), key = lambda (k, v): b.index(k) if k in b else a.keys().index(k))
but, I think it is wrong.
so I can I do it using python.
Thanks
Upvotes: 2
Views: 137
Reputation: 123453
I think this does what you want:
a = {1:2,2:3,3:4}
b = [3,1]
print ([(k,a[k]) for k in b if k in a] +
[(k,a[k]) for k in a if k not in b])
Output:
[(3, 4), (1, 2), (2, 3)]
This would also work:
head, tail = [], []
any((head if k in b else tail).append((k,a[k]))
for k in (b + [k2 for k2 in a if k2 not in b]))
print head+tail
I wouldn't call it sorting a
-- maybe ordering it.
Upvotes: 0
Reputation: 304147
A good way to handle the special cases is to use tuples as the sort key
>>> a = {1: 2, 2: 3, 3: 4}
>>> b= [3, 1]
>>> sorted(a.items(), key=lambda (k,v):(0, b.index(k)) if k in b else (1,))
[(3, 4), (1, 2), (2, 3)]
if b is long, it's a good idea to create a dict to speed up the index lookups
>>> b_dict = {k:v for v, k in enumerate(b)}
>>> sorted(a.items(), key=lambda (k,v):(k not in b_dict, b_dict.get(k)))
[(3, 4), (1, 2), (2, 3)]
Upvotes: 2
Reputation: 16049
Try this:
import sys
sorted(a.items(), key = lambda (k, v): b.index(k) if k in b else sys.maxint)
For the keys that are not in b
, we return a very large value, which places them at the end of the sorted result.
Upvotes: 4
Reputation: 56863
I'm not sure about the expected output that you want, but maybe this helps:
a = {1:2,2:3,3:4}
b = [3,1]
r = [(x,a[x]) for x in b if x in a]
which gives r
as a list:
[(3, 4), (1, 2)]
If this is not the expected output, maybe it helps as an intermediate step.
Upvotes: 0