Tuple to dictionary in python by using text file

I have a code which returns a dictionary with the names as the keys and the corresponding values which are tuples of numbers. The first number after the name controls how many numbers are in the corresponding tuple (the numbers included in the tuple are taken from the left to right). For example, the line of text "Ali 6 7 6 5 12 31 61 9" has 6 as the first number after the name and this line of text becomes the dictionary entry with the keyword "Ali" and the corresponding value is a tuple made up of the next six integers "Ali": (7, 6, 5, 12, 31, 61).

This is the film I'm taking the code from

  Bella 5 2 6 2 2 30 4 8 9 2
  Gill 2 9 7 54 67
  Jin 3 26 51 3 344 23 
  Elmo 4 3 8 6 8
  Ali 6 7 6 5 12 31 61 9

the expected output is

Ali : (7, 6, 5, 12, 31, 61)
Bella : (2, 6, 2, 2, 30)
Elmo : (3, 8, 6, 8)
Gill : (9, 7)
Jin : (26, 51, 3)

so i've done like this

   def get_names_num_tuple_dict(filename):      
   file_in = open(filename, 'r')
   contents = file_in.read()
   file_in.close()
   emty_dict = {}
   for line in contents:
      data = line.strip().split()
      key = data[0]
      length = int(data[1])
      data = tuple(data[2:length + 2])
      emty_dict[key] = data

   return emty_dict

But I'm having this error length = int(data[1]) IndexError: list index out of range

Can anyone please help? That will be really helpful. I'm a bit weak with the dictionary as learning for the first time.


Use following code:

def get_names_num_tuple_dict(filename):      
   emty_dict = {}
   with open(filename) as f:
      for line in f:
         data = line.strip().split()
         key = data[0]
         length = int(data[1])
         data = tuple(data[2:length + 2])
         emty_dict[key] = data

   return emty_dict


print(get_names_num_tuple_dict('my_filename'))

Output:

{'Bella': ('2', '6', '2', '2', '30'), 'Gill': ('9', '7'), 'Jin': ('26', '51', '3'), 'Elmo': ('3', '8', '6', '8'), 'Ali': ('7', '6', '5', '12', '31', '61')}

Here is what happens:

contents = file_in.read()

Reads your file into string. When you loop over this string it will go character by character and give you IndexError: list index out of range .

Basically try using:

for line in file_in:
    data = line.strip().split()
        ...
链接地址: http://www.djcxy.com/p/5454.html

上一篇: 用于从.h文件中的头文件分离实现的脚本

下一篇: 通过使用文本文件在Python中对元组进行字典