Python编程:使用Dictionaries隔离数据



我正在尝试使用python完成一个赋值。目标是使用字典来解析.txt文件,并隔离时间和temp。将它们放在字典中,然后找到最高temp及其对应的时间。

我已经完成了作业,但我不知道如何让它只打印最高的。相反,我正在打印前三名。

pycharm输出

fname = raw_input("Enter the file name: ")
try:
    fhand = open(fname)
except:
    print "The file can not be opened."
    exit()
climate = dict()        #creates dictionary
count = 0
largest = None  # Iteration variable to find highest temp
high = 0
for line in fhand:
    count += 1              #count variable to get rid of line 1
    if count == 1:      #may be causing it to iterate 3x????
        continue
    words = line.split()            # splits into tokens
    time = words[0] + words[1]      # combines time and am/pm
    climate[time] = words[2]        # matches time to temp making key-value pair
for key in climate:
        if climate[key] > largest:    # Iterates through key-value's finding largest and placing it in largest container
            largest = climate[key]
            print 'The highest temperatures occurred at', key, 'reaching', largest, 'Fahrenheit.'
fhand.close()

这应该可以实现您想要的:

high_key = None
largest = 0
for key in climate:
        if climate[key] > largest:    # Iterates through key-value's finding largest and placing it in largest container
            largest = climate[key]
            high_key = key
if high_key:
    print 'The highest temperatures occurred at', high_key, 'reaching', largest, 'Fahrenheit.'

最新更新