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
Dunes source
share