How to convert all_timezones to another format

Asked

Viewed 21 times

0

I need to convert the timezones pytz to the following format below, but I’m having trouble doing this with python. How does this type of conversion work?

from pytz import all_timezones

time_zones = [{
       u'value': u'1',
       u'text': (u'Africa/Abidjan')
   }, {
     u'value': u'2',
     u'text': (u'Africa/Accra')
  }...]

The print output(all_timezones) is:

('all_timezones', ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers' ... ])

1 answer

1


In fact all_timezones is a list of timezone names. If you want to create another list containing dictionaries (which in turn contain a sequential number and the name of the Timezone), just do:

timezones = []
for i, tz in enumerate(all_timezones):
    timezones.append({ 'value': str(i + 1), 'text': tz })

With enumerate you scroll through the list and its contents at the same time.

That said, I don’t know what the advantage of creating dictionaries value is a sequential number, as lists already have their elements in sequential numerical indices (the difference is that it starts at zero instead of 1). If the idea is to search for an element by the numerical index, a list is much better for it (just do all_timezones[numero] - recalling that the first element is at zero, the second at index 1, etc).


Another alternative is to use a comprehensilist on, much more succinct and pythonic:

timezones = [ { 'value': str(i + 1), 'text': tz } for i, tz in enumerate(all_timezones) ]
  • 1

    Thank you very much for all explanations, I will study on list comprehension, I agree your explanation regarding advantage. But as they created in the project this way I can not change.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.