Convert a text file into a dictionary

2019-09-20 16:21发布

问题:

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?

  1. Open it
  2. Check if string s = any key in the dictionary
  3. If it is, then string s = the object linked to the aforementioned key.
  4. If not, nothing happens
  5. File closes.

I've tried the following code for dividing them with commas, but the output was incorrect. It made the combination of key and object in the text file into a single key and single object, effectively duplicating it:

Code:

file = open("foo.txt","r")
dict = {}

for line in file:
    x = line.split(",")
    a = x[0]
    b = x[0]
    dict[a] = b

Incorrect output:

key:object, key:object
key2:object2, key2:object2
key3:object3, key3:object3

Thank you

回答1:

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


回答2:

# -*- coding:utf-8 -*-
key_dict={"key":'',"key5":'',"key10":''}
File=open('/home/wangxinshuo/KeyAndObject','r')
List=File.readlines()
File.close()
key=[]
for i in range(0,len(List)):
    for j in range(0,len(List[i])):
        if(List[i][j]==':'):
            if(List[i][0:j] in key_dict):
                for final_num,final_result in enumerate(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"



回答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()