How to create a dictionary through a string

Asked

Viewed 1,298 times

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?

  • 1

    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.

  • 2

    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': {}}]

  • So you could build an employee to access the dictionaries in dicts of the elements of the original list.

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

  • If you resonated your problem inspired by my idea, you managed to understand the essence of my solution, no?

  • Okay, I was sleepy and had understood that you had already solved :-), I answered the question with my idea for the solution.

Show 2 more comments

2 answers

2


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

Since file names are dynamic, I believe a good approach would be to have a dictionary of dictionaries. A centralizing dictionary where the contents of all the files will be.


I will use example the following file and contents:

  • plum.json

      {"nome": "Ameixa"}
    
  • banana json.

      {"nome": "Banana"}
    
  • cashew.json

      {"nome": "Caju"}
    

First step would be to read these files from the folder where they are (I’ll assume they are in the same python script folder).

You can use the function os.scandir to iterate over all entries in a file (files, directories, symlinks, etc). Ex.:

import os

with os.scandir() as it:
    for entry in it:
        pass

Now that we are iterating on the entries, we have to select only the files that interest us, which are the JSON files

import os

with os.scandir() as it:
    for entry in it:
        if entry.is_file() and entry.name.endswith('.json'):
            pass

This is the time to:

  • extract the file name to use as key in our dictionary "centralizer"
  • read the contents of the file
  • do the Parsing of JSON using json.loads()
  • assign the result of Parsing to the dictionary

The final code would look like this:

import os
import json
from pprint import pprint  # apenas para fins de apresentação

frutas = dict()

# Lê todas as entradas do diretório atual
with os.scandir() as it:
    # Itera sobre estas entradas
    for entry in it:
        # Se for um arquivo JSON
        if entry.is_file() and entry.name.endswith('.json'):
            # Abre o arquivo para leitura
            with open(entry.path, 'r') as f:
                key = entry.name[:-5]  # elimina o ".json" do nome do arquivo
                value = f.read()  # lê todo o conteúdo do arquivo
                frutas[key] = json.loads(value)  # faz o parsing do JSON e salva no dicionário

pprint(frutas)

Repl.it of the working code.

The result is:

{'ameixa': {'nome': 'Ameixa'},
 'banana': {'nome': 'Banana'},
 'caju': {'nome': 'Caju'}}

1

Putting into practice the idea presented in the comments of the question:

First let’s create a function that receives a list of dictionaries and a key, through the key the dictionary is returned:

def get_dict(dicts, key):
    for d in dicts:
        result = d.get(key)
        if result:
            return result
    return None 

Now let’s create the list and dictionaries:

lista = ['ameixa', 'banana', 'caju']

# Criando os dicionarios:
dicts = []
n = 10
for x in lista:
    dicts.append({x: {n}})
    n+=1

# Apresentando o conteudo dos dicionarios
print('Conteúdo dos dicionários:',dicts, sep='\n') 

Exit:

Conteúdo dos dicionários:
[{'ameixa': {10}}, {'banana': {11}}, {'caju': {12}}]

Now let’s access the dictionary banana through the list:

print('Dic ref ao segundo elemento da lista:',get_dict(dicts, lista[1]), sep='\n') 

Exit:

Dic ref ao segundo elemento da lista:
{11}

See working on repl.it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.