Can someone assist me on the proper placement of an if statement on my dict. I am try to flag any user that is NY and have them come first in the dictionary. I am able to get sort by name which I require as well but not clear how to flag any NY users
names_states = {
'user1': 'CA',
'user2': 'NY',
'user7': 'CA',
'guest': 'MN',
}
for key in sorted(names_states.iterkeys()):
2 ... print "%s : %s" %(key, names_states[key])
3 ...
4 user1 : CA
5 user2 : NY
6 guest : MN
7 user7 : CA
sorted(names_states.iteritems(), key=lambda x: (x[1] != 'NY', x[0]))
Here is an approach that first pushes the NY values to the top, while still sorting by user name as the first key, and the state as the secondary key:
{'bill': 'NY',
'frank': 'NY',
'guest': 'MN',
'user1': 'CA',
'user2': 'NY',
'user7': 'CA'}
def keyFunc(x):
if names_states[x] == 'NY':
return (False, x)
return (x, names_states[x])
sorted(names_states.iterkeys(), key=keyFunc)
# ['bill', 'frank', 'user2', 'guest', 'user1', 'user7']
Note: Sticking with the key
approach here is faster than defining a custom cmp
function. The key function will only be run once for each item, whereas a cmp function will be run every single combination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With