user1478335
user1478335

Reputation: 1839

Python forming a dictionary from a text file with value being a tuple

import pickle
def create_dict():



    final_image_dict = {}
    f_name = "./images/image_dict.txt"

    handle = open(f_name, encoding = 'utf-8')
    for line in handle:
        if line.startswith(" ") : continue
        terms = line.split(": ")
        term = terms[0]
        dict_tuple = terms[1].split(",")
        caption = dict_tuple[0]
        image = dict_tuple[1]

        final_image_dict[term] = final_image_dict.get(term, dict_tuple)


    with open("./images/final_image_dict.txt", "wb") as image_infile:
        pickle.dump(final_image_dict, image_infile)

I am trying , with the above function, to create a dictionary in the format of key:(caption, image) from a text file of the following format:

addugliare:  (Coil a rope = Avvolgere a spire una cima,addugliare.gif),
admiral:  (classic anchor= ancora classico,admiral.gif),
aft:  (verso la poppa, aft.gif),
alberatura: (mastage,alberatura.gif),
albero: (mast = albero, albero.gif),
ancore: (anchors, anchore.gif),
andatu: (tacks, andatu.gif),
armi: (sailing craft, armi.gif),
bearing: (rilevamento , bearing.gif), etc

My problem is in creating the tuple for the value. The above gives {'mooring': [' (ormeggio', ' mooring.gif)', '\n'], 'knot(speed)': [' (nodo(velocità)', ' knot.gif)', '\n'], 'addugliare': [' (Coil a rope = Avvolgere a spire una cima', 'addugliare.gif)', rather than 'mooring': ('ormeggio','mooring.gif') which is the format that I want. Could someone please help. I have also tried (caption, image) which seems to return a tuple of a tuple which doesn't work for me either

Upvotes: 0

Views: 28

Answers (1)

John Coleman
John Coleman

Reputation: 52008

Maybe something like this (modified to ignore blank lines and trailing whitespace):

def extractTuple(s):
    s = s.strip()
    n = len(s)
    p = s[1:n-1].split(',')
    return (p[0].strip(),p[1].strip())

def dictFromFile(fname):
    f = open(fname)
    lines = f.read().split('\n')
    f.close()
    d = {}
    for line in lines:
        line = line.strip()
        if line.endswith(','):
            line = line[:len(line)-1]
            k,v = line.split(':')
            d[k] = extractTuple(v)
    return d

With your example data:

>>> d = dictFromFile("test.txt")
>>> for k in d: print(k,':',d[k])

admiral : ('classic anchor= ancora classico', 'admiral.gif')
armi : ('sailing craft', 'armi.gif')
addugliare : ('Coil a rope = Avvolgere a spire una cima', 'addugliare.gif')
aft : ('verso la poppa', 'aft.gif')
andatu : ('tacks', 'andatu.gif')
alberatura : ('mastage', 'alberatura.gif')
albero : ('mast = albero', 'albero.gif')
ancore : ('anchors', 'anchore.gif')
bearing : ('rilevamento', 'bearing.gif')

Upvotes: 1

Related Questions