Rico
Rico

Reputation: 6052

A more elegant way of creating tuples of tuples from lists

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?

Upvotes: 1

Views: 94

Answers (2)

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))

Upvotes: 0

defuz
defuz

Reputation: 27611

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'))

Upvotes: 4

Related Questions