Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dict. if statement

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
like image 778
user1388430 Avatar asked Dec 28 '22 01:12

user1388430


2 Answers

sorted(names_states.iteritems(), key=lambda x: (x[1] != 'NY', x[0]))
like image 156
Florian Mayer Avatar answered Jan 14 '23 11:01

Florian Mayer


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.

like image 38
jdi Avatar answered Jan 14 '23 09:01

jdi