Dump Cake
Dump Cake

Reputation: 300

Python: How to create a dictionary named after a list entry?

I'm new to python so this is probably a dumb question. I'm sure the answer is in the docs or another thread on stack overflow, but I could not find it.

I have a list: dict_list = ['first_dict', 'second_dict', 'third_dict']

I need a way create a dictionary for each entry in this list and then reference it later using its list index. So, by referencing dict_list[0], I want to be able to create a new dictionary first_dict = {}.

Then, I want to be able to reference that dictionary again later by using dict_list[0], then assign keys and values to first_dict.

This dict_list will contain anywhere from 1 to 1000 entries.

Upvotes: 1

Views: 139

Answers (2)

kindall
kindall

Reputation: 184171

What do you need the names for? The answer is, you don't. When you start thinking about programmatically assigning a bunch of variable names, especially if those names have numbers in them, you are almost always better off just making a list or some other container.

dict_list = [{} for x in xrange(3)]

Now dict_list[0] is one dictionary, dict_list[1] is another, and so on. This makes them easy to iterate over and access without hackery like globals() or eval().

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

you can use globals():

In [54]: dict_list = ['first_dict', 'second_dict', 'third_dict']

In [55]: for x in dict_list:
    globals()[x]=dict()
   ....:     
   ....:     

In [57]: dict_list=[globals()[x] for x in dict_list]

In [58]: dict_list[0]['key']='value'  #add key to first_dict 

In [60]: first_dict       
Out[60]: {'key': 'value'}

In [63]: first_dict is dict_list[0]  #dict_list[0] and first_dict are same objects
Out[63]: True

Upvotes: 0

Related Questions