Sakizzle
Sakizzle

Reputation: 9

Create a dictionary from a given string in a text file

I have a file with a string in this format: .B:13&A:4&I:1&I:!&H:|-|&H:}{&B:!3&H:[-]&&

It begins with a "." ends with a "&", separates each entry key-value pair with a "&" and finally separates each key from its corresponding value with a ":"
This is what I have so far:

// read the data
filehndl = open("text.dat") filedata = filehndl.read() filehndl.close()

but I'm not sure how to strip and split the data to create the dictionary. Any help would be appreciated!

Upvotes: 0

Views: 119

Answers (3)

Skycc
Skycc

Reputation: 3555

1 liner version assume your filedata will be 1 liner also

1st split the dict items by & after strip off the . and &, then built the dict splitting the key value pair by :

filedata = r'.B:13&A:4&I:1&I:!&H:|-|&H:}{&B:!3&H:[-]&&'
d = dict( i.split(':') for i in filedata.strip('.&\r\n').split('&') )
# {'A': '4', 'I': '!', 'B': '!3', 'H': '[-]'}

but this does not take care the repeated items with same key, for example, you have repeated key B, the later B:!3 will override the previous B:13

Upvotes: 1

luisurrutia
luisurrutia

Reputation: 586

I'm going to assume that your file only has one single line and that you aren't handle quoting, so then you can do it with a generator comprehension:

with open("yourfile.txt") as file:
    data = file.read().strip()
    if data.startswith(".") and data.endswith("&"):
        clean = data.lstrip(".").rstrip("&")
        print dict(item.split(":") for item in clean.split("&"))

The important line here, is:

dict(item.split(":") for item in clean.split("&"))

This is going to split your string by the & character, and then split again by : character, to finally "convert" the list in a dictionary.

Upvotes: 0

Walter Martin
Walter Martin

Reputation: 27

You can strip the first and last characters with:

filedata = filedata[1:-1]

Then split with:

entries = filedata.split('&')

Then split entries up and put them in a dict:

out_dict = {}
for entry in entries:
    entry_array = entry.split(':')
    out_dict[entry_array[0]] = entry_array[1]

So altogether you have

filehndl = open("text.dat")
filedata = filehndl.read()
filedata = filedata[1:-1]

entries = filedata.split('&')

out_dict = {}
for entry in entries:
    entry_array = entry.split(':')
    out_dict[entry_array[0]] = entry_array[1]

# out_dict is what you now want to work with

filehndl.close()

Upvotes: 1

Related Questions