There is a txt file

smt1 abcd smt2 efg smt3 hijkl 

How to open it in a similar way in Python?

 dct = { 'smt1': {'a', 'b', 'c','d'}, 'smt2': {'e', 'f', 'g'}, 'smt3': {'h', 'i', 'j','k','l'} } 

Thank!

  • Do you want the values ​​to be set? (as shown in the example in question) Or is it enough to have simple lists? - jfs
  • @jfs apparently the author is no longer needed. surely he needs duplicate lists - while1pass

2 answers 2

A file is an iterator over lines in Python, so it can be passed into the loop directly:

 d = {} with open("файл.txt") as file: for line in file: key, *value = line.split() d[key] = value 

with -construction closes the file when exiting the block to avoid resource leaks even if an error occurs.

.split() splits a line into an arbitrary space, allowing you to use for example tabs ( '\t' ) or several spaces in a row to separate fields in a line.

*value is Python 3 syntax. See What does it mean * (asterisk) and ** double star in Python?

    As I understand it, you need to get data from a text file in the form of a dictionary. It is unlikely that you need a set-set, and you need the following result:

     dict = { 'smt1': ['a', 'b', 'c', 'd'], 'smt2': ['e', 'f', 'g'], 'smt3': ['h', 'i', 'j', 'k', 'l'] } 

    Open the file for reading and split line by line.

     file = open("text") onstring = file.read().split("\n")[:-1] 

    The result is a list of the following form

     ['smt1 abc d', 'smt2 ef g', 'smt3 hijk l'] 

    The resulting list is sorted, each element is divided by the separator - " " . The first element of the partition will be the key of our dictionary, the list of the rest will be the value.

     dict = dict() for item in onstring: key = item.split(" ")[0] value = item.split(" ")[1:] dict[key] = value file.close() 

    We get the desired result

     {'smt1': ['a', 'b', 'c', 'd'], 'smt2': ['e', 'f', 'g'], 'smt3': ['h', 'i', 'j', 'k', 'l']} 

    Just keep in mind that if the key matches, its value will be overwritten.

    • one
      split by default is done by spaces. - Nick Volynkin