How to Convert a File into a Dictionary

How to convert text file into dict?

Since the data is in JSON format, you can use the json module to parse it into a Python dictionary. In Python 2 strings aren't Unicode, so you'll also need to convert all Unicode strings in the input into that format.

Here's how to do that using a helper function. Note that the order of items in the result may not be the same as the input because in Python 2, dictionaries don't preserve the order-of-insertion.

import json
from pprint import pprint
import sys

if sys.version_info[0] > 2:
raise RuntimeError('Requires Python 2')

def unicode_convert(obj):
""" Convert unicode data to string in object and return it. """

if isinstance(obj, unicode):
obj = obj.encode()
elif isinstance(obj, list):
obj = map(unicode_convert, obj)
elif isinstance(obj, dict): # Converts contents in-place.
for key, value in obj.items(): # Copy of dict's (key, value) pairs (Py2)
del obj[key]
if isinstance(key, unicode):
key = key.encode()
if isinstance(value, (unicode, list, dict)):
value = unicode_convert(value)
obj[key] = value

return obj

with open('personal_info.json') as file:
info = json.load(file) # Parse JSON object into Python dictionary.
line_dict = {key: value for key, value in unicode_convert(info).items()}

pprint(line_dict)

most efficient way to convert text file contents into a dictionary in python

Just by using the csv module :

import csv

with open("userinfo.txt") as file:
list_id = csv.reader(file)
userinfo_dict = {key:passw for key, passw in list_id}

print(userinfo_dict)
>>>{'user1': 'pass1', 'user2': 'pass2'}

with open() is the same type of context manager you use to open the file, and handle the close.

csv.reader is the method that loads the file, it returns an object you can iterate directly, like in a comprehension list. But instead of using a comprehension list, this use a comprehension dict.

To build a dictionary with a comprehension style, you can use this syntax :

new_dict = {key:value for key, value in list_values} 
# where list_values is a sequence of couple of values, like tuples:
# [(a,b), (a1, b1), (a2,b2)]

Convert a file into dictionary

It is the same as the one in the link you mentioned in the comments. Except you unpack three values in a line instead of two.

test.txt (your text file)

a 1 4
b 2 5
c 3 6

Your code:

d = {}
with open("test.txt") as f:
for line in f:
(key, val1, val2) = line.split()
d[key] = (int(val1), int(val2))

print(d)

gives you,

{'a': (1, 4), 'b': (2, 5), 'c': (3, 6)}

Convert a text file into a dictionary list

titles = ["title","price","count"]
[dict(zip(titles, [int(word) if word.isdigit() else word for word in line.strip().split()])) for line in open("in_file.txt").readlines()]

or:

titles = ["title","price","count"]
[dict(zip(titles, [(data:=line.strip().split())[0], *map(int, data[1:])])) for line in open("in_file.txt").readlines()]

your approach(corrected):

in_filepath = 'in_file.txt'

def data_dict(in_filepath):
res = []
with open(in_filepath, 'r') as file:
for line in file.readlines():
title, price, count = line.split()

d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
res.append(d)

return res

data_dict(in_filepath)

why? because

  1. ->
    d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)

is out of for loop and run only once and when ‍‍for be finished and then you have just one element


  1. you return your last element and didn't use others and use must create a list and append every element at the last line of for loop (saving) and at last, return result

@Rockbar approach:

import pandas as pd

list(pd.read_csv("in_file.txt", sep=" ", header=None, names=["title","price","count"]).T.to_dict().values())


Related Topics



Leave a reply



Submit