How to convert a file into a dictionary?

Posted on

Question :

How to convert a file into a dictionary?

I have a file comprising two columns, i.e.,

1 a 
2 b 
3 c

I wish to read this file to a dictionary such that column 1 is the key and column 2 is the value, i.e.,

d = {1:'a', 2:'b', 3:'c'}

The file is small, so efficiency is not an issue.

Answer #1:

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val
Answered By: Vlad H

Answer #2:

This will leave the key as a string:

with open('infile.txt') as f:
  d = dict(x.rstrip().split(None, 1) for x in f)

Answer #3:

You can also use a dict comprehension like:

with open("infile.txt") as f:
    d = {int(k): v for line in f for (k, v) in [line.strip().split(None, 1)]}
Answered By: wim

Answer #4:

def get_pair(line):
    key, sep, value = line.strip().partition(" ")
    return int(key), value

with open("file.txt") as fd:    
    d = dict(get_pair(line) for line in fd)
Answered By: tokland

Answer #5:

By dictionary comprehension

d = { line.split()[0] : line.split()[1] for line in open("file.txt") }

Or By pandas

import pandas as pd 
d = pd.read_csv("file.txt", delimiter=" ", header = None).to_dict()[0]
Answered By: Samer Ayoub

Answer #6:

IMHO a bit more pythonic to use generators (probably you need 2.7+ for this):

with open('infile.txt') as fd:
    pairs = (line.split(None) for line in fd)
    res   = {int(pair[0]):pair[1] for pair in pairs if len(pair) == 2 and pair[0].isdigit()}

This will also filter out lines not starting with an integer or not containing exactly two items

Answered By: Holger Bille

Answer #7:

import re

my_file = open('file.txt','r')
d = {}
for i in my_file:
  g = re.search(r'(d+)s+(.*)', i) # glob line containing an int and a string
  d[int(g.group(1))] = g.group(2)
Answered By: VGE

Answer #8:

If you love one liners, try:

d=eval('{'+re.sub(''[s]*?'','':'',re.sub(r'([^'+input('SEP: ')+',]+)','''+r'1'+''',open(input('FILE: ')).read().rstrip('n').replace('n',',')))+'}')

Input FILE = Path to file, SEP = Key-Value separator character

Not the most elegant or efficient way of doing it, but quite interesting nonetheless 🙂

Answered By: srami

Leave a Reply

Your email address will not be published.