0

How can I create a Dictionary from my while loop below? infile reads from a file called input, which has the following content:

min:1,23,62,256

max:24,672,5,23

sum:22,14,2,3,89

P90:23,30,45.23

P70:12,23,24,57,32

infile = open("input.txt", "r")
answers = open("output.txt", "w")

while True:
    line = infile.readline()
    if not line: break
    opType = line[0:3]
    numList = (line[4:len(line)])
    numList = numList.split(',')

What I'm trying to do is basically 2 lists, one that has the operation name (opType) and the other that has the numbers. From there I want to create a dictionary that looks like this

myDictionary = {
    'min': 1,23,62,256,
    'max': 24,672,5,23,
    'avg': 22,14,2,3,89,
    'P90': 23,30,45.23,
    'P70': 12,23,24,57,32,
}

The reason for this is that I need to call the operation type to a self-made function, which will then carry out the operation. I'll figure this part out. I currently just need help making the dictionary from the while loop.

I'm using python 2.7

1 Answer 1

1

Try the following code.

I believe, you would need the 'sum' also in the dictionary. If not, just add a condition to remove it.

myDictionary = {}
with open('input.txt','r') as f:
    for line in f:
        x = line.split(':')[1].rstrip().split(',')
        for i in xrange(len(x)):
            try:
                x[i] = int(x[i])
            except ValueError:
                x[i] = float(x[i])
        myDictionary[line.split(':')[0]] = x
print myDictionary
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This is exactly what I wanted. I just added orderedDict myDictionary = {} myDictionary = collections.OrderedDict()
Thanks, can you please accept my answer as the rigt one. Your help is appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.