How to add elements from a file to a dictionary?

Asked

Viewed 37 times

0

Hello, I’m making a program that has to take all the elements of a file (which has several lines) and put in a dictionary like this:

file (1st line) => Mercado1,biscuit,4.3,milk,3.2,juice,7.1,chocolate,6.4,detergent,3.2,beer,6.4,butter,8.7 dictionary => { market 1:{biscuit:4.3, milk:3.2, etc }, market 2:{etc} }

So first I did a function to create the inside dictionaries, those of each market (each row), but when I run it is only storing the last row of the file:

def criaDicProdutos():
    arq = open('MercadosProdutos.txt','r', encoding = 'utf-8')
    dic = {}
    for linha in arq:
        lista_produtos = linha.strip().split(',')
        for i in range (1,len(lista_produtos)-1):
            teste = lista_produtos[i].isalpha()
            if teste == True:
                dic[lista_produtos[i]] = lista_produtos[i+1]
    arq.close()
    print(dic)
    return  di

Below is the txt file I’m using:

Cheap,biscuit,4.3,milk,3.2,juice,7.1,chocolate,6.4,detergent,3.2,beer,6.4,butter,8.7 Ultrak,biscuit,3.5,milk,3.3,juice,8.9,chocolate,6.9,detergent,4.2,beer,6.4,butter,8.7 Market,biscuit,4.5,milk,3.2,juice,7.5,chocolate,6.6,detergent,3.8,beer,6.5,butter,9.2 Preferred,biscuit,4.65,milk,3.4,juice,8.1,chocolate,8.1,detergent,3.3,beer,6.5,butter,8.9 Choice,biscuit,5.2,milk,3.3,juice,8.3,chocolate,7.5,detergent,3.9,beer,6.4,butter,8.6

1 answer

0

Just scroll through each line of your file and separate each item from the line by the comma with the string method called split. In doing so, you can create a key using the first item in the list, which will initially store an empty dictionary and then store the products and values.

To store the products in the sub-dictionary, we can use for...range to make the position element x be the dictionary key and the position element x + 1 be the value.

The problem is that if we do it with a simple range(1, len(linha)), the elements that should only be values will also become key. This is because we are not skipping the traveled positions and at some point, the key would receive the element in the value position.

{"biscoito": "4.3", "4.3": "leite", "leite": "3.2", "3.2": "suco",...}

So what we should do is move to the parameter step of function range() the value 2, for all odd position elements to be keys and even position elements to be values.

See below the code:

def obter_dicionario(lines):

    dicionario = {}

    for line in lines:

        line = line.split(",")    # Separa os itens pela vírgula
        dicionario[line[0]] = {}  # Cria sub-dicionário

        for i in range(1, len(line), 2):

            chave = line[i]
            valor = line[i + 1]

            dicionario[line[0]][chave] = valor

    return dicionario


with open("<nome_do_arquivo>") as file:
    dicionario = obter_dicionario(file.readlines())
  • Great, I got it! Thank you so much

Browser other questions tagged

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