如何在Python中的for循环中创建唯一的词典?

时间:2015-07-13 18:15:40

标签: python for-loop dictionary

我对Python比较陌生。我有很多文件,对于每一个文件,我想创建一个包含文件信息的字典。我目前的代码是:

thespefiles = glob.glob('*.SPE')
for filename in thespefiles:
    barename = filename.replace('.SPE', '')
    #does operation to retrieve outputwpsx and outputwpsz
    #does operation to retrieve value

    barename +'_dictionary' = {
        'filename': filename,
        'barename': barename,
        'readcounts': value,
        'wpsx': outputwpsx,
        'wpsz': outputwpsz,
    }

然而,行barename + '_dictionary'出现了错误:

  

“语法错误:无法分配给运算符”。

据我所知,字典通常没有引号分配,但当我使用barename_dictionary时,它说:

  

“NameError:name'splate2_008_006_dictionary'未定义”

当我在整个循环之外测试它时,

(plate2_008_006是特定的游标之一)。

所以,我的问题是,有没有办法从单个for循环创建一堆独特的词典?我到处寻找。

2 个答案:

答案 0 :(得分:3)

将你的内部词汇放在外部词典中:

thespefiles = glob.glob('*.SPE')
file_dict = {}
for filename in thespefiles:
    barename = filename.replace('.SPE', '')
    #does operation to retrieve outputwpsx and outputwpsz
    #does operation to retrieve value

    file_dict[barename] = {
        'filename': filename,
        'barename': barename,
        'readcounts': value,
        'wpsx': outputwpsx,
        'wpsz': outputwpsz,
    }

动态变量名称是可能的,但要避免。对于这样的情况,最好使用像dict这样的容器数据结构来键入你正在构建的内部词汇。

答案 1 :(得分:0)

你为什么这样做?您将拥有一堆新变量,您将无法识别和获取它们。您提供的代码,无论是第一个还是第二个都无效。您试图将新值设置为字符串(barename +“_ dictionary”),这是不可能的。您可以使用 setitem ()方法(例如字典,列表,...)仅将新值设置为变量或对象。 在第二种情况下,您将每个新字典放在名为“barename_dictionary”的变量中。由于裸名已经存在,奇怪的事情发生了。为什么这会引发错误,我不确定。从理论上讲,这不应该发生。但是,显然它确实存在并且很糟糕。

然而,你想做的事情是可能的。这是如何完成的。

# There are two ways:
# 1. Construct the code string and execute it:
codestr  = barename+"_dictionary = "
codestr += "{'barename': 'blah-blah', 0: 1234}"
exec codestr
# Or (2.), simply add the new variable with a dictionary manually to a wanted namespace:
globals()[barename+"_dictionary"] = {"barename": "blah-blah"}

# In both cases variable names have to be within Python naming rules.
# Your filenames are a little odd for that. Change them!

请记住kojiro说的话。如果你真的没有,请不要这样做!