Python dict. if statement

Can someone help me in placing the if statement on my dict correctly. I am trying to tag any user who is NY and include them in the dictionary. I can get sorting by name, which I also need, but it's not clear how to tag all 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
+3
source share
5 answers
sorted(names_states.iteritems(), key=lambda x: (x[1] != 'NY', x[0]))
+4
source

Here's an approach that first pushes NY values ​​up, and sorts by username as the first key, and 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']

. key , cmp. , cmp .

+3

, . , , .

names_states = {
    'user1': 'CA',
    'user2': 'NY',
    'user7': 'CA',
    'guest': 'MN',
}

def ny_compare(x, y):
    if names_states[x] == 'NY':
        if names_states[y] == 'NY':
            return cmp(x,y)
        else:
            return -1
    elif names_states[y] == 'NY':
        return 1
    return cmp(x,y)


for key in sorted(names_states.iterkeys(), cmp=ny_compare):
    print "%s :  %s" %(key, names_states[key])
+2

sorted(names_states.iteritems(), key=lambda (name, state): (state != 'NY', name))
+1
for key, value in sorted(names_states.iteritems(), 
            key=lambda (key, value): ((0 if value == 'NY' else 1), key)):
    print((key,value))

iteritems() / . /. , , . , , - , 'NY' . , , , ..

, , , .

You may want to subclass the dict and add an additional method that provides keys, values, or key / value pairs in the desired order.

So you can have something simple:

names_states = MyDict({
  'user1': 'CA',
  'user2': 'NY',
  'user7': 'CA',
  'guest': 'MN',
})

for key, value in names_states.iteritems_with_given_values_first('NY'):
    ...

class MyDict(dict):

    def __init__(self, *args, **kwargs):
        super(MyDict, self).__init__(*args, **kwargs)

    def iteritems_with_given_values_first(self, preferred_value):
        for key, value in sorted(names_states.iteritems(), 
                key=lambda (key, value): ((0 if value == preferred_value else 1), key)):
            yield key, value
0
source