views:

46

answers:

1

In the following dictionary,can the elements be sorted according the last prefix in the key

opt_dict=(
{'option1':1,
 'nonoption2':1,
 'nonoption3':12,
 'option4':6,
 'nonoption5':5,
 'option6':1,
 'option7':1,
  })

    for key,val in opt_dict.items():
           if "answer" in key:  //match keys last prefix and print output

               print "found option 1,4,6,7" //in ascending order
           elif "nonanswer" in key: //match keys last prefix and print output
               print "found option 2,3,5 "  //in ascending order

Thanks..

A: 
for k,v in sorted(opt_dict.items(),
                  key = lambda item: int(item[0][len("option"):])
                            if item[0].startswith("option")
                            else int(item[0][len("nonoption"):])
                    ):
    print k,v

Prints:

option1 1
nonoption2 1
nonoption3 12
option4 6
nonoption5 5
option6 1
option7 1
Paul McGuire
There appears to be a syntax error in the line if item[0].startswith("option")
Hulk
What version of Python are you running? Works on 2.5.4.
Paul McGuire
Maybe you're using a Python version <2.5 where the `x = a if b else c` syntax was introduced?
jellybean
I am using 2.4.3
Hulk