creating a variable with name as same as the name of items in list

Viewed 535

just a stupid question out of curiosity.

Lets say there's a list with elements as

fruits_lst = ['apples','oranges','bananas','guavas']

Now is it possible to create separate separate dictionaries but with the names as the names of elements in the list?

desired result:

apples=dict()
oranges=dict()
bananas=dict()
guavas=dict()

I know one could easily do it by looking at the names of the elements, but what i want to achieve is somehow the program picks up the element names while iterating through it and then creates empty dictionaries with the same names. Is it possible? Kindly guide me through..

3 Answers

Use dict instead of globals

Use of global variables is not recommended practice. Much cleaner and easily maintainable is a dictionary of dictionaries. For example, using a dictionary comprehension:

fruits_lst = ['apples', 'oranges', 'bananas', 'guavas']

d = {fruit: {} for fruit in fruits_lst}

Then access a particular inner dictionary via d['apples'], d['oranges'], etc.

See this answer for an explanation why this is useful, and here for another example.

Everything in Python is a dictionary, even the scope. You can use globals() for it:

fruits_lst = ['apples','oranges','bananas','guavas']
globals().update({name : dict() for name in fruits_lst})
apples["foo"] = 10
print(apples)

Results are:

{'foo': 10}

Here's a short way, but let me warn you this isn't a good way to defining variables.

fruits_lst = ['apples','oranges','bananas','guavas']

for fruit in fruits_lst:
    globals()[fruit] = dict()

Now you can access them directly,

>>> apples
{}
>>> oranges
{}

and so on...

Related