简体   繁体   中英

how to read the contents of file and convert it into dictionary in python

I have a text file (applications.txt) containing n number of lines of data (with 2 delimiters) in the below format.

1) mytvScreen|mytvScreen|Mi TV,Mí TV, My Tv, TV
2) watchNextScreen|watchNextScreen|Seguir viendo,Mi TV Seguir viendo
3) recordingsScreen|recordingsScreen|Grabaciones,Mis Grabaciones,Mi TV

Note: 1,2,3 are just line numbers for reference. Original file doesn't contain the number.

I am trying to write a function that would read each line and convert it into a dictionary using the value before the first delimiter and the values after the second delimiter, like the example shown below.

eg:

The below line one should be converted into dictionary as expected below. 1) mytvScreen|mytvScreen|Mi TV,Mí TV, My Tv, TV

Expected Format:

mytvScreen : Mi TV, Mí TV, My Tv, TV

Also, Upon giving any value which are comma separated, it should return the value before the colan .

Eg:

When the value Mi TV is given, it should return mytvScreen or for the other comma separated values also, it should return mytvScreen

I was able to read the file and print the values as expected.

But not sure how can i convert each line into a dictionary.

with open('applications.txt') as f:
                for line in f:
                        details=line.split("|",2)
                        print (details[0] + ' : '+ details[2])

Your Help is highly appreciated.

you should be adding items to dictionary, one of the approach is given below.

s_dict= dict()
with open('applications.txt') as f:
      for line in f:
          details=line.split("|",2)
          print (details[0] + ' : '+ details[2])
          s_dict[details[0]]  = details[2]
      print (s_dict)

I build a file-object to mimic applications.txt content:

>>> import io
>>> f = io.StringIO("""mytvScreen|mytvScreen|Mi TV,Mí TV, My Tv, TV
... watchNextScreen|watchNextScreen|Seguir viendo,Mi TV Seguir viendo
... recordingsScreen|recordingsScreen|Grabaciones,Mis Grabaciones,Mi TV""")

Your file is obviously a csv file, thus you should use the csv module to parse it:

>>> import csv
>>> reader = csv.reader(f, delimiter='|')

The last part is just a dict-comprehension:

>>> {row[0]: row[2] for row in reader}
{'mytvScreen': 'Mi TV,Mí TV, My Tv, TV', 'watchNextScreen': 'Seguir viendo,Mi TV Seguir viendo', 'recordingsScreen': 'Grabaciones,Mis Grabaciones,Mi TV'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM