ljman711
ljman711

Reputation: 45

Sorting python dictionary based on value index and in alphabetical order

I am trying to sort a python dictionary and having a bit of an issue. The dictionary is in the following format: {UID: Name, Type}.

dic1={"720155": ["CAT", "Software"], "356d05": ["ESF", "Software"], "3b3758": ["DBA", "Software"], "9649db": ["Fun", "Software"], "96493f": ["Eagle", "Software"], "99701d": ["Pas", "Software"], "964971": ["Debug", "Software"], "b6f315": ["Bap", "Software"], "a0a824": ["Server", "Software"], "1e00sa": ["Adobe", "Software"], "8c8dd2": ["EXIT", "Software"], "cc1dfg": ["email", "Software"]}

I use sorted(dic1.iteritems(), key=operator.itemgetter(1)) but this allows the "email" item to be last instead of after "Debug" name. see below:

[('1e00sa', ['Adobe', 'Software']), 
('b6f315', ['Bap', 'Software']), 
('720155',['CAT', 'Software']), 
('3b3758', ['DBA', 'Software']), 
('964971', ['Debug', 'Software']), 
('356d05', ['ESF', 'Software']), 
('8c8dd2', ['EXIT', 'Software']), 
('96493f', ['Eagle', 'Software']), 
('9649db', ['Fun', 'Software']), 
('99701d', ['Pas', 'Software']), 
('a0a824', ['Server', 'Software']), 
('cc1dfg', ['email', 'Software'])]

I tried using the sorted(sorted(dic1.iteritems(), key=operator.itemgetter(1)), key=str.lower), but this gives an error that a tuple was received instead of a string.

Any ideas? I cannot change how the dictionary is formed, it must remain as it is.

Upvotes: 3

Views: 99

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123560

You need a more complex key function:

sorted(dic1.iteritems(), key=lambda i: i[1][0].lower())

This sorts on the first element of the value, lowercased.

Demo:

>>> from pprint import pprint
>>> dic1={"720155": ["CAT", "Software"], "356d05": ["ESF", "Software"], "3b3758": ["DBA", "Software"], "9649db": ["Fun", "Software"], "96493f": ["Eagle", "Software"], "99701d": ["Pas", "Software"], "964971": ["Debug", "Software"], "b6f315": ["Bap", "Software"], "a0a824": ["Server", "Software"], "1e00sa": ["Adobe", "Software"], "8c8dd2": ["EXIT", "Software"], "cc1dfg": ["email", "Software"]}
>>> pprint(sorted(dic1.iteritems(), key=lambda i: i[1][0].lower()))
[('1e00sa', ['Adobe', 'Software']),
 ('b6f315', ['Bap', 'Software']),
 ('720155', ['CAT', 'Software']),
 ('3b3758', ['DBA', 'Software']),
 ('964971', ['Debug', 'Software']),
 ('96493f', ['Eagle', 'Software']),
 ('cc1dfg', ['email', 'Software']),
 ('356d05', ['ESF', 'Software']),
 ('8c8dd2', ['EXIT', 'Software']),
 ('9649db', ['Fun', 'Software']),
 ('99701d', ['Pas', 'Software']),
 ('a0a824', ['Server', 'Software'])]

Upvotes: 3

Related Questions