Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mass variable declaration and assignment in Python

Trying to create a batch of dictionaries:

January = {}
February = {}
March = {}

I would rather do something like: January, February, March... = {}

which of course doesn't work.

Ultimately, I'm wanting to create a dictionary of these dictionaries:

MONTHS_DICT = {'01':January,'02':February...}

Its not a ton of code to do it line by line but I'm just learning Python and.... doing something repetitive typically tells me it can be done more efficiently in some other way.

Thoughts?

p.s. I'm working with python 2.x but if using 3 for this example would be of some help, that's not a problem.

like image 489
chris Avatar asked Dec 03 '22 02:12

chris


2 Answers

January, February, March = {}, {}, {}

That's a little bit more concise way to do the initial declaration.

like image 65
chisaipete Avatar answered Jan 04 '23 09:01

chisaipete


Why do you want to month names as variables if you don't use them? You could simply write

month_dicts = [{} for _ in range(12)] # twelve dicts
numbers = ["%02d" % x for x in range(1,13)] # strings "01" ... "12"

# the dict
MONTHS_DICT = dict(zip(numbers, month_dicts))
# the dict for March
MONTHS_DICT["03"]
like image 36
Jochen Ritzel Avatar answered Jan 04 '23 07:01

Jochen Ritzel