Reply to post 'Tryign to add a valkue to a set'

russ.pobox at gmail.com russ.pobox at gmail.com
Mon Jun 10 11:34:00 EDT 2013


for key, value in sorted(months.items(), key=lambda x:x[1]):
    print("""'\t<option value"%s">%s</option>'\n""" % (value, key))


Explanation:
- - - - - - 
dict.items is a method associated with dicts just like dict.keys or dict.values, and returns a list of (key, value) pairs.

sorted and some other builtin functions have an optional key argument, which tells the function what exactly to look at when sorting the sequence. (I say sequence because you can sort a string or tuple or dict and get a list back in return). In this case we use a simple lambda function to tell it to look at the value not the key (i.e. (key, value)[1] returns value)

Alternatively you could do this.

def get_value(item):
    return item[1]

for key, value in sorted(months.items(), key=get_value):
    ...etc...

You might also wonder what this would do

for key, value in sorted(months.items()):
    ...etc...

Which becomes a question of what would something like this do

sorted([(1,3), (2,2), (3,1)])

Well sorted is a function that expects to get some iterable (sequence of some kinda items) to sort. If those items happens to be sequences themselves, like (key, value) which is a sequence of two items, then it's only going to care about the first item and ignore the rest (i.e ignore value).

So the above will return
[(1,3), (2,2), (3,1)] which as far as sorted() is concerned, is already sorted.


About the string being printed:
- - - - - - - - - - - - - - - - 
I'm not sure why or if you want a single quotation around the entire element to be printed as well but if so then that's how I'd do it. The \t is for a tab. You also don't have to worry about adding newlines because print will print each statement on a newline anyways by default unless you tell it otherwise by specifying the sep argument.

Sorry my first post, I said allot didn't I.



More information about the Python-list mailing list