Text file to Tuple to Dictionary in Python -


i have text file contains following information:

britney 2 3 4 5 1 23 6 jessica 5 1 5 3 2 33 1 5 2 5 61 2 mathew 2 33 1 4 2 5 5 2 3  sofia 8 3 1 2 3 52 1 5 2 3 51 25 23 1 2 6 

i supposed write function takes name , assigns key in dictionary

as value of key, that's bit more complicated.

the function needs read through numbers, first number (starting left right) indicates how many numbers in tuple. , goes through number , picks second number - nth number.

for example.

britney 2 3 4 5 1 23 6 

the first number 2 indicates next 2 number tuple value key britney. britney has value (3, 4)

likewise:

sofia 8 3 1 2 3 52 1 5 2 3 51 25 23 1 2 6 

sofia has value (3, 1, 2, 3, 52, 1, 5, 2)

i thinking along lines of:

input_file = open("namesandnumbers.txt", "r") the_dict = {} line in input_file:     initial = line.replace("\n","").split(" ")     key = initial[0] 

but can't figure out next, , unsure using split(" ") there space between name , numbers, between numbers well.

this should work you. on right track, part missing slicing string up. i'd suggest read more here: cutting , slicing strings in python

input_file = open("namesandnumbers.txt", "r") the_dict = {} line in input_file:     initial = line.replace("\n","").split(" ")     key = initial[0]     number = int(initial[1])     value = tuple([int(x) x in initial[2: number + 2]])     the_dict[key] = value 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -