1

I'm using Python 2.7 and want to create a choice in a Django form. I have a dictionary of the items I want in the choice drop-down but want to know the most pythonic way to handle this.

Here is my solution:

my_dict = {
    'AL' : 'Alabama',
    'AK' : 'Alaska',
    etc...
}

my_list = []
for value in (my_dict):
    my_list.append('({0}, {1})'.format(value, gateways.get(value)))

my_tuple = '({0})'.format(','.join(my_list))

print my_tuple


(('AL', 'Alabama'),('AK', 'Alaska'),etc...)

This will work, but it didn't look very elegant to me. Can someone suggest a better solution?

1
  • 1
    You are creating strings, not tuples.. And your output will be ((AL, Alabama), (AK, Alaska), ...) as coded (no quotes).
    – Martijn Pieters
    Oct 10, 2012 at 10:07

2 Answers 2

4

In fact, you do not necessarily need a tuple for create a choice, quite a list:

>>> d = {'AL' : 'Alabama', 'AK' : 'Alaska',}
>>> d.items()
[('AK', 'Alaska'), ('AL', 'Alabama')]

For tuple:

>>> tuple(d.items())
(('AK', 'Alaska'), ('AL', 'Alabama'))
2
  • I can dig it...Thanks. This is much more elegant.
    – Rico
    Oct 10, 2012 at 10:27
  • Sorry defuz, I missunderstood the conversation, apologizes for all.
    – Netwave
    Oct 10, 2012 at 10:47
0

You may use a list comprehension to replace the loop

my_list = ['({0}, {1})'.format(value, gateways.get(value)) for value in my_dict]

And even write it directly as a generator expression in the generation of my_tuple

my_tuple = '({0})'.format(','.join('({0}, {1})'.format(value, gateways.get(value)) for value in my_dict))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.