Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"}

?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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' }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading