Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将一对键和值添加到dict_Python_List_Dictionary - Fatal编程技术网

Python 将一对键和值添加到dict

Python 将一对键和值添加到dict,python,list,dictionary,Python,List,Dictionary,我正在尝试将上面的输入格式格式化为一个dicts列表 基本上我想要的是将文件的内容转换成一个dict列表。但是,每次运行代码时,我都会得到相同的输出:[{'Similar:similar5',Score:score5',component:smi}]。这意味着只创建了一个dict,而我的目标是创建5个dict(每行一个)。 有人能帮我修一下吗 dt = [] # Creates a list to store dicts with open('sample_text.out') as f: #

我正在尝试将上面的输入格式格式化为一个dicts列表

基本上我想要的是将文件的内容转换成一个dict列表。但是,每次运行代码时,我都会得到相同的输出:[{'Similar:similar5',Score:score5',component:smi}]。这意味着只创建了一个dict,而我的目标是创建5个dict(每行一个)。 有人能帮我修一下吗

dt = [] # Creates a list to store dicts
with open('sample_text.out') as f: # Opens the target text file
    for line in f:

        if line.startswith('Compound'):
            smi = line.split()[1]
            dt.append({'Compound' : smi}) # Add smi as a value in a dict inside the list 'dt'

        else: # This part will iterate over the next few lines, split them and add them to the growing list of dicts

            new_line = line.split()
            similar = new_line[0]
            score = new_line[1]
            print new_line
            for dicts in dt:
                dicts['Similar'] = similar
                dicts['Score'] = score


print dt

这试图修复代码中的一些设计缺陷,并输出您想要的内容:

dictionaries = [] # Creates a list to store dicts

with open('sample_text.out') as input_file:  # Opens the target text file

    compound = None

    for line in input_file:

        if line.startswith('Compound'):
            _, smi = line.split()
            compound = smi
        else:
            similar, score = line.split()
            dictionaries.append({'Similar': similar, 'Score': score})
            dictionaries[-1]['Compound'] = compound

print(dictionaries)

您希望这段代码在什么时候创建第二个dict?(dt:dicts['teste']=new_line中dicts的
是什么意思?)这个代码中唯一创建dict的部分是
{'component':smi}
,它只对以
'component'
开头的行执行。我真正想要的是创建5个dict(每行一个)。但是我没有理解正确。我认为dt中的dicts:dicts['teste']=新行将更新以前创建的dict。如果您添加一个示例输入文件以及您希望看到的数据结构,可能会有所帮助。谢谢您!输出良好。但是,我不理解行u3;,smi=line.split()。为什么我不能写smi=line.split()?@MarcosSantana,你有
smi=line.split()[1]
,这很好,我只是做了一个转换到
,smi=line.split()。这两种方法都有效,我只是尽量避免使用数字。