简体   繁体   中英

convert text file into dictionary -Python

I am given a .txt file which looks like this..

2:rain 3:odd 5:yes 6:go

I need to convert it into a dictionary.

This is what I have done so far.

 words_dict = {}
 file = open(filename, "r")
 for word in file:
      k, v = word.split(":")
      words_dict[k.strip()] = v.strip()                
 file.close()
 return words_dict

However, when i go and print the dictionary it does not match my expected output of {2: 'rain', 3: 'odd', 5: 'yes', 6: 'go'}

l="2:rain 3:odd 5:yes 6:go".split()
{x.split(":")[0]:x.split(":")[1]  for x in l}
list_ = [x for x in open('text.txt').read().split()]

dict_ = {k: v for k, v in [x.split(':') for x in list_]}


# list_ = ['2:rain', '3:odd', '5:yes', '6:go']
# dict_ = {'2': 'rain', '3': 'odd', '5': 'yes', '6': 'go'}

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