How to Separate Data in Dictionary from a . txt (Python)

Asked

Viewed 1,183 times

1

I have a text file (attachment.txt), which I have to store in a dictionary, with Name as key and phone, value. the file has the following information:

--- nome telefone ---
Ailton-1197765445 Josefa-2178655434

I used the following code:

ref_files = open("anexo.txt", "r")
for linha in ref_files:
    valos = linha.split()
    print(valos[0],valos[:0],valos[1:])

ref_files.close()

but it returns the values like this: Ailton-1197765445 [] ['Josefa-2178655434']

I created the dictionary but the return is the same:

dic = { k.split()[0]:k.split()[1:] for k in ref_files.readlines() }

Could someone help me with that? Grateful.

  • It is important to note that when you use slicers on a list, such as you are doing when you do [1:], you get a list as a result.

  • Are there always two names per line or can there be more? The first line of the file, --- nome telefone ---, is also in the archive or just put in question to exemplify?

  • @Andersoncarloswoss are always two names per line, and the first line is also in the file.

1 answer

0


def monta_dicionario(caminho=None):
    with open(caminho, "r") as anexo:
        dic = {}
        for linha in  anexo.readlines()[1:]:
            nomes = linha.split(" ")
            for nome_tel in nomes:
                val = nome_tel.split('-')
                dic[val[0]] = val[1]

    return dic

if __name__ == '__main__':
    dic = monta_dicionario('./anexo.txt')
    print(dic)
  • Thank you! Everything is as I wanted, thank you

Browser other questions tagged

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