How am I to convert the .txt file into dictionary – Python

I’ve a .txt file with the data in the following format:

{"user_id": "user_id", "category": "category"}
{"user_id": "123456789", "category": "Hardware"}
{"user_id": "987654321", "category": "Equipment"}

How am I to convert it to the following dictionary:

{"123456789":"Hardware"}
{"987654321":"Equipment"}

?

>Solution :

first create a list to hold the data for you

second open the file and convert each line to a dictionary object

finally add the object to your list

( since you don’t need the first line of your file, you may pop the first element of your list )

result = [] # for holding the data

with open('file','r') as data: # open your file in read mode

    for line in data.readlines(): # iterate over lines

        temp_json = json.loads(line) # create a dict object from each line upon every iteration 

        result.append({ temp_json['user_id'] : temp_json['category'] }) # append the object to your list 
    
result.pop(0) # pop the first element wich is { 'user_id':'category' }

Leave a Reply