当前位置: 动力学知识库 > 问答 > 编程问答 >

Creating a Dictionary from a while loop (Python)

问题描述:

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

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: