2017-07-30 27 views
0

我需要知道什么是将具有未知键和值(格式可以是txt)的文件转换为字典(或列表)的最简单方法,例如第一个将键的值转换为可以进一步用其余值来进行计算的变量。我下面不正确的代码:将文件转换为字典并将特定键的值用作变量

file = input("Insert name of the file.") 
    try: 
     disc = open(file, 'r') 
     my_dictionary = {} 
     for line in disc: 
      k,v = line.rstrip().split() #in case of empty rows in file and 
      my_dictionary [k]= int(v) # spaces between keys and values 
     amount_k = len(my_dictionary) # lenght of dict 
     first_value = my_dictionary.item(1) 
     i=1 
     for sub in my_dictionary: 
      my_dictionary[sub] = my_dictionary[sub]/((1/i)*first_value*amount_k) 
      i += 1 
    except OSError: 
      print("the" , file ,"could not be read") 

我猜变量FIRST_VALUE不正确,之所以上面我的代码不能正常工作或全部(回溯:FIRST_VALUE = my_dictionary.item(1) AttributeError的:“快译通”对象没有属性'项目')?回想一下,我想知道如何将值转换为变量,我应该在这种情况下使用列表或类似的字典而不是字典(利弊)? 非常感谢提前!

+0

你是什么意思*未知文件*?文件的*格式*是什么? –

+1

你的“except”块在哪里? –

+0

请添加你的追踪。 – nivhanin

回答

0

的第一项应my_dictionary.items()[0]

参见items方法doc