0

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

1
  • You could use a list of dictionaries. In this case your dictionary_1 = {}, would be dictionaries[0] = {}. Does this cover what you want to achieve? Commented Nov 19, 2022 at 10:11

2 Answers 2

0

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...

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.