简体   繁体   中英

How can I add variables into a dictionary with a loop?

I'm pretty new to python and I'm trying to create loops that are capable of doing all the work that I did by hand. Essentially creating all the line'#' variables and assigning them the particular line of text from the file 'game_catch.txt' which reads something like this:

Curving                 10
Dodgeball               15
Keep Away               5
Kin-Ball                7
Prisoner Ball           21
Quidditch               30
Rundown (aka Pickle)    12
Yukigassen              18
Handball                25

(With the spaces being Tabs, if that makes any difference)

Then creating another loop that assigns the value of the line'#' variables to str'#' variables while splitting all the spacing away. (I cannot modify the file because in other computers it will be the same as the one I posted above, so I have to do this step)

Then, and more importantly because this is where I'm completely stuck, making a loop for doing all the nitty gritty work of turning the str'#' variables into something the sports dictionary can pick up and then read as {'Curving': 10}

Here I provided the code I'm currently using and trying to simplify:

file = open('game_catch.txt','r')
line1 = file.readline()
line2 = file.readline()
line3 = file.readline()
line4 = file.readline()
line5 = file.readline()
line6 = file.readline()
line7 = file.readline()
line8 = file.readline()
line9 = file.readline()

str1 = line1.split()
str2 = line2.split()
str3 = line3.split()
str4 = line4.split()
str5 = line5.split()
str6 = line6.split()
str7 = line7.split()
str8 = line8.split()
str9 = line9.split()

sports = {}

key = ''
for i in str1[0:-1] :
    key += i + ' '

key = key[0:-1]

sports[key] = int(str1[-1])

Sorry for the long post, I just wanted to provide as much detail as possible. Feel free to let me know if there are more efficient ways of doing this. Thanks

You can get a basic structure (which will keep the scores as strings) by iterating over the file, splitting each line, and sending the pairs in that generator to dict() :

with open('game_catch.txt') as f:
    d = dict(line.rsplit(maxsplit=1) for line in f)

You can cast the scores as integers by creating a generator to split each line, then unpacking each line and using the int() function:

with open('game_catch.txt') as f:
    d = dict((name, int(score)) for name, score in (line.rsplit(maxsplit=1) for line in f))

You can use the literal comprehension syntax instead of the dict() function:

with open('game_catch.txt') as f:
    d = {name:int(score) for name, score in (line.rsplit(maxsplit=1) for line in f)}

The most important part is, of course, to check out a tutorial so that you can understand what these code snippets are doing and make sense of the explanations. Loops and data structures are particularly important.

The following will turn you txt file into a dictionary, taking into consideration that some of the sports names are comprised of multiple words:

lines = [line.rstrip('\n').split() for line in open('C:/Users/Simon/Desktop/test.txt')]

sports = {}

for el in lines:
    number = el.pop()
    curItem = ' '.join(el)

    sports[curItem] = int(number)

print sports

That will give something like this:

{'Curving': 10, 'Keep Away': 5, 'Dodgeball': 15}
file = 'game_catch.txt'
sports = {}

with open(file) as f:
 for line in f:
  parts = line.split()
  sports[parts[0]] = int(parts[-1])

hope this helps.

Example Here

trans_dict = {'one':'wahed', 'two':'itnen', 'three':'talata'}

       print "ITER ITEMS", trans_dict.iteritems()

       for key, val in trans_dict.iteritems():

                   print "KEY", key

                   print "VAL", val

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM