简体   繁体   English

如何通过循环将变量添加到字典中?

[英]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. 我是python的新手,我正在尝试创建能够完成我手工完成的所有工作的循环。 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: 基本上创建所有行'#'变量,并从文件'game_catch.txt'中为它们分配特定的文本行,该文件内容如下:

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) (空格为Tabs,如果有任何区别)

Then creating another loop that assigns the value of the line'#' variables to str'#' variables while splitting all the spacing away. 然后创建另一个循环,将“#”变量的值分配给str'#'变量,同时将所有间距分开。 (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} 然后,更重要的是因为这是我完全卡住的地方,做了一个循环,用于完成将str'#'变量转换为体育字典可以拾取的内容的所有细节,然后读作{'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() : 您可以通过迭代文件,分割每一行,并将该生成器中的对发送到dict()来获得基本结构(将分数保持为字符串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: 您可以通过创建生成器来分割每一行,然后解压缩每一行并使用int()函数将分数转换为整数:

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: 您可以使用文字理解语法而不是dict()函数:

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: 考虑到一些体育名称由多个单词组成,以下内容将把你的txt文件变成字典:

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'} 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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