-2

I'm trying to create many dictionaries in a for loop in Python 2.7. I have a list as follows:

sections = ['main', 'errdict', 'excdict']

I want to access these variables, and create new dictionaries with the variable names. I could only access the list sections and store an empty dictionary in the list but not in the respective variables.

for i in enumerate(sections):
    sections[i] = dict()

The point of this question is. I'm going to obtain the list sections from a .ini file, and that variable will vary. And I can create an array of dictionaries, but that doesn't work well will the further function requirements. Hence, my doubt.

Parisa Rai
  • 155
  • 2
  • 4
  • 9

2 Answers2

3

To clear dictionaries

If the variables in your list are already dictionaries use:

for var in sections:
  var.clear()

Note that here var = {} does not work, see Difference between dict.clear() and assigning {} in Python.

To create new dictionaries

As long as you only have a handful of dicts, the best way is probably the easiest one:

main = {} #same meaning as main = dict() but slightly faster
errdict = {}
excdict = {}
sections = [main,errdict,excdict]

The variables need to be declared first before you can put them in a list.

For more dicts I support @dslack's answer in the comments (all credit to him):

sections = [dict() for _ in range(numberOfDictsYouWant)] 

If you want to be able to access the dictionaries by name, the easiest way is to make a dictionary of dictionaries:

sectionsdict = {}
for var in sections:
   sectionsdict[var] = {}

You might also be interested in: Using a string variable as a variable name

Community
  • 1
  • 1
Robin Spiess
  • 1,480
  • 9
  • 17
  • @StoryTeller It is unused, but how can I make a for loop without a variable to loop over? An alternative would be to use `for _ in range()` but that's not much of a difference. – Robin Spiess Dec 22 '15 at 09:57
  • 1
    There's a big difference, the latter is more idiomatic, to the point that pylint understands it. But if you frown on it for the problems that may sometimes come with it, than use the other idiom of `unused_*` for throwaway variables. – StoryTeller - Unslander Monica Dec 22 '15 at 10:05
  • @StoryTeller Changed the answer, thanks for your input. – Robin Spiess Dec 22 '15 at 10:08
  • To be a bit pitty main = {} and main = dict() is not excactly the same. There are slight differences which you can find if you disassemble them. As far as i know the main difference is that dict() is a c build in and they differ in reserving memory at creation time – Stefan Reinhardt Dec 22 '15 at 11:05
  • @StefanReinhardt True, I have also read, that using `{}` seems to be up to 6 times faster than `dict()` in some python versions. – Robin Spiess Dec 22 '15 at 11:52
  • @RobinSpiess Yes that's true, I read that it is because of allocation and that the dict() version would be slightly faster when adding elements later – Stefan Reinhardt Dec 22 '15 at 12:29
  • @RobinSpiess, I'm really sorry for causing so much confusion, and I thank you so much for the pains you took for the answer. I learned a lot from it. – Parisa Rai Dec 24 '15 at 14:23
3

Robin Spiess answered your question beautifully.

I just want to add the one-liner way:

section_dict = {sec : {} for sec in sections}

For maintaining the order of insertion, you'll need an OrderedDict:

from collections import OrderedDict
section_dict = OrderedDict((sec, {}) for sec in sections)
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • On trying this insert the section_dict appears to be in the reverse order of the list sections. I tried the following and it did not work: `sorted(section_dict.items())` This obviously didn't solve my purpose `sorted(section_dict.iteritems())` This method sorted the dictionary in the oppposite order, the same as the **wrong** insert order – Parisa Rai Dec 28 '15 at 07:21
  • 1
    @ParisaRai, I assure you that the items are inserted in the correct order, however a python dictionary is an **unordered** data structure. If you need to maintain the order of insertion than have a look in the [`collections`](https://docs.python.org/2/library/collections.html#ordereddict-objects) module – StoryTeller - Unslander Monica Dec 28 '15 at 09:13