1
Good afternoon,
I wonder if it is possible to create a dictionary through a string, for example:
I create a loop for inside a list and this loop will always give me a name:
lista = ['ameixa', 'banana', 'caju']
for i in lista:
print(i)
output = ameixa
banana
caju
Is there a way to create a dictionary through these strings ? Following the same example from above I would like my outputs to be:
ameixa = {}
banana = {}
caju = {}
Is that even possible? My goal is to import and transform all the jsons I use in my code into dictionaries the moment I start my application.
**** Edit ****
Exactly as mentioned in the comments I would like to create dictionaries dynamically.
To illustrate my situation better:
I have several files called "plum.json", "banana.json" and "caju.json".
What I want to do is take the content of each of these jsons and turn it into a dictionary that will always receive the same name ( plum.json within my code will become a dictionary called plum).
It was based on this need that I thought of creating a list with the name of each of these jsons and using a loop to create empty dictionaries because once I have the created dictionaries I can do the manipulation.
If you happen to know any other way of transforming jsons into dictionaries dynamically I will be very grateful, but for now is the idea that I am investing in.
That doesn’t make much sense to me. How will you know
caju
is in the original list and therefore there is the dictionary?– Woss
If I understand correctly you want to dynamically create dictionaries with the names of the fields that are in the list. There is a way to do it but as stated you will have no way of knowing if there are dictionaries, unless, there is a pattern that is always the same.
– sant0will
Without knowing its context I would guess that the solution might be, create an empty dicts list, loop the list
['ameixa', 'banana', 'caju']
and then add the dictionaries whose keys would be the elements of that list, at the end you would have something like this:[{'ameixa': {}}, {'banana': {}}, {'caju': {}}]
– Sidon
So you could build an employee to access the dictionaries in
dicts
of the elements of the original list.– Sidon
Sidon, if I can turn my list of names into dictionaries like this, I can already do what I need, but I couldn’t figure out how to execute this idea that you suggested. Thank you for your attention.
– Filipe Gonçalves
If you resonated your problem inspired by my idea, you managed to understand the essence of my solution, no?
– Sidon
Okay, I was sleepy and had understood that you had already solved :-), I answered the question with my idea for the solution.
– Sidon