jalyper
jalyper

Reputation: 81

Can I pass two conditionals to build a key/value pair in the same dictionary?

I have two if-statements that need to be run in order to get all the information I need to build a dictionary. I have a text file 'file.txt' which has values separated by lines. A basic representation of my code would look like:

dict = {}
    for line in 'file.txt':
        line = line.strip()
            if line.startswith('Key: '):
                key = print(line)

and at this point I need the other if-statement to get me the value which needs to be paired with 'key' that I just defined:

elif line.startswith('Value: '):
    value = print(line)

Now I need to update the dictionary, but I'm out of scope and I don't know how to tie key and value together in the same dictionary, whose values were obtained by going line-by-line through 'file.txt' to ensure the keys are paired with the correct values. Is there a way to do this?

The file (when open) looks like a list separated by newlines: "Filename: name, Size: 200MB, Version: 2.2.2, etc..." This pattern repeats. So I need to grab 'Filename', skip 'Size', grab 'Version', and put the two together as a key/value pair.

Upvotes: 0

Views: 70

Answers (1)

Prune
Prune

Reputation: 77860

Find the key. Keep looking until you find a value. If your data file is a simple alternation, the "None" stuff in this code won't matter. If you have intermittent errors in this respect, you can harness the "None"

dict = {}
infile = open("in", 'r')
for line in infile:
    line = line.strip()
    line = line.split(',')
    print "line:  ", line
    for field in line:
        field = field.strip()
        print "field:", field
        if field.startswith('Filename: '):
            key = field.split(':')[1]
            value = None

        elif field.startswith('Version: '):
            value = field.split(':')[1]
            if key is not None:
                dict[key] = value
                value = None
                key = None

print dict

Here is the output, given your input line:

line:   ['Filename: name', ' Size: 200MB', ' Version: 2.2.2']
field: Filename: name
field: Size: 200MB
field: Version: 2.2.2
{' name': ' 2.2.2'}

Upvotes: 1

Related Questions