Python - Sorting a Tuple-Keyed Dictionary by Tuple Value -
i have dictionary constituted of tuple keys , integer counts , want sort third value of tuple (key[2]) so
data = {(a, b, c, d): 1, (b, c, b, a): 4, (a, f, l, s): 3, (c, d, j, a): 7} print sorted(data.iteritems(), key = lambda x: data.keys()[2])
with desired output
>>> {(b, c, b, a): 4, (a, b, c, d): 1, (c, d, j, a): 7, (a, f, l, s): 3}
but current code seems nothing. how should done?
edit: appropriate code
sorted(data.iteritems(), key = lambda x: x[0][2])
but in context
from collections import ordered dict data = {('a', 'b', 'c', 'd'): 1, ('b', 'c', 'b', 'a'): 4, ('a', 'f', 'l', 's'): 3, ('c', 'd', 'j', 'a'): 7} xxx = [] yyy = [] zzz = ordereddict() key, value in sorted(data.iteritems(), key = lambda x: x[0][2]): x = key[2] y = key[3] xxx.append(x) yyy.append(y) zzz[x + y] = 1 print xxx print yyy print zzz
zzz unordered. know because dictionaries default unordered , need use ordereddict sort don't know use it. if use checked answer suggests 'tuple index out of range' error.
solution:
from collections import ordereddict data = {('a', 'b', 'c', 'd'): 1, ('b', 'c', 'b', 'a'): 4, ('a', 'f', 'l', 's'): 3, ('c', 'd', 'j', 'a'): 7} xxx = [] yyy = [] zzz = ordereddict() key, value in sorted(data.iteritems(), key = lambda x: x[0][2]): x = key[2] y = key[3] xxx.append(x) yyy.append(y) zzz[x + y] = 1 print xxx print yyy print zzz
dictionaries unordered in python. can use ordereddict
.
you have sort like:
from collections import ordereddict result = ordereddict(sorted(data.iteritems(),key=lambda x:x[0][2]))
you need use key=lambda x:x[0][2]
because elements tuples (key,val)
, obtain key
, use x[0]
.
this gives:
>>> data = {('a', 'b', 'c', 'd'): 1, ('b', 'c', 'b', 'a'): 4, ('a', 'f', 'l', 's'): 3, ('c', 'd', 'j', 'a'): 7} >>> collections import ordereddict >>> result = ordereddict(sorted(data.iteritems(),key=lambda x:x[0][2])) >>> result ordereddict([(('b', 'c', 'b', 'a'), 4), (('a', 'b', 'c', 'd'), 1), (('c', 'd', 'j', 'a'), 7), (('a', 'f', 'l', 's'), 3)])
edit:
in order make zzz
ordered well, can update code to:
data = {('a', 'b', 'c', 'd'): 1, ('b', 'c', 'b', 'a'): 4, ('a', 'f', 'l', 's'): 3, ('c', 'd', 'j', 'a'): 7} xxx = [] yyy = [] zzz = ordereddict() key, value in sorted(data.iteritems(), key = lambda x: x[0][2]): x = key[2] y = key[3] xxx.append(x) yyy.append(y) zzz[x + y] = 1 print xxx print yyy print zzz
Comments
Post a Comment