I have the following list of values: Numbers = [1,2,3,4]. Is it possible to create a dictionary with the same name as the values contained in the list?
Example: dictionary_1 = {} dictionary_2 = {} .... dictionary_Number.. {}
I would like to create these dictionaries automatically, without creating them manually, reading the numbers contained in the list
CodePudding user response:
You may use the keyword exec
in python. Here is an example of your solution,
List = [1, 2,3]
for ele in List:
dic = f"Dictionary_{ele}"
exec(dic " = {}")
print(Dictionary_1, Dictionary_2, Dictionary_3, sep='\n')
you may use it according to you, but the disadvantage for it is that you will need to use exec
every time you need to use it or you must know what would be the name outcome of the first use of exec
...
I hope I helped...
CodePudding user response:
Use the inbuild functions and remember that a dictionary needs a tuble (key & value):
Example-Code:
Numbers = [1,2,3,4]
Numbers_dict = dict.fromkeys(Numbers,"dict_value")
print(Numbers_dict)
This will output:
{'1': 'dict_value', '2': 'dict_value', '3': 'dict_value', '4': 'dict_value'}
If you want to get a single dictonaries for each list-value, you first have to create for each list-value an empty variable. After this you have to fill this empty vairables within a loop.