Skip to content Skip to sidebar Skip to footer

Convert A Text File Into A Dictionary

I have a text file in this format: key:object, key2:object2, key3:object3 How can I convert this into a dictionary in Python for the following process? Open it Check if string s

Solution 1:

m={}                            
for line in file:
    x = line.replace(",","")     # remove comma if presenty=x.split(':')               #split key and value
    m[y[0]] = y[1]

Solution 2:

# -*- coding:utf-8 -*-
key_dict={"key":'',"key5":'',"key10":''}
File=open('/home/wangxinshuo/KeyAndObject','r')
List=File.readlines()
File.close()
key=[]
for i inrange(0,len(List)):
    for j inrange(0,len(List[i])):
        if(List[i][j]==':'):
            if(List[i][0:j] in key_dict):
                for final_num,final_result inenumerate(List[i][j:].split(',')):
                    if(final_result!='\n'):
                        key_dict["%s"%List[i][0:j]]=final_result

print(key_dict)

I am using your file in "/home/wangxinshuo/KeyAndObject"

Solution 3:

You can convert the content of your file to a dictionary with some oneliner similar to the below one:

result = {k:v for k,v in [line.strip().replace(",","").split(":") for line in f if line.strip()]}

In case you want the dictionary values to be stripped, just add v.strip()

Post a Comment for "Convert A Text File Into A Dictionary"