更改字典的格式

时间:2017-03-01 17:42:09

标签: python csv dictionary

我正在尝试编写一个函数,它将带有以下格式的字典写入一个csv文件,该文件包含每个测试的列(第一个字典中的键)和不同污染物的行(键中的键)正在测试的子词典。每个单元格将包含子字典的值。

output=table.csv
dictionaryEx={'run2.csv': {' ph': 25, ' escherichia coli': 14, ' enterococci': 1},
 'run1.csv': { ' enterococci': 7, ' ph': 160, ' nickel': 3, 
 ' dieldrin': 4, ' barium': 1, ' trichloroethylene': 1, }


def writeFile(dictionary)
    with open(output,'w') as outputFile:
    polDict={}
    for element in dictionary:
        print element
        for pollutant,value in element.values():
            polDict[pollutant]={element:value}
    for element in polDict:
        outputFile.write(pollutant+','+ polDict.values())
outputFile.close()

现在,我试图通过制作一个新词典来实现这一目标,但我正在努力解决从中写作的问题。是否可以使用其他数据结构? csv应该如何看待

  

&#34;&#34; ,run2.csv,run1.csv \ n ph,25,160 \ n escherichia coli,14,&#34;&#34; \ n肠球菌,1,7 \ n镍,&#34;&#34;,3 < / p>

enter image description here

2 个答案:

答案 0 :(得分:0)

此版本适用于Python 3.5.1:

output="table.csv"
dictionaryEx={\
        'run2.csv': {' ph': 25, ' escherichia coli': 14, ' enterococci': 1},\
        'run1.csv': {' enterococci': 7, ' ph': 160, ' nickel': 3, ' dieldrin': 4, ' barium': 1, ' trichloroethylene': 1}}

def writeFile(dictionary):
    with open(output,'w') as outputFile:
        # Write the title line.
        outputFile.write(",")
        for key in dictionary.keys():
            outputFile.write(key + ",")
        outputFile.write("\n")

        # Generate a sorted unique list of pollutants.
        pollutants = []
        for d in dictionary.values():
            for k in d.keys():
                pollutants.append(k)
        # This sorts the list and removes duplicates.
        pollutants = sorted(set(pollutants))

        # For each possible pollutant, output the pollutant's
        # value for each CSV.
        for p in pollutants:
            outputFile.write(p + ",")
            for csv in dictionary.keys():
                if p in dictionary[csv]:
                    outputFile.write(str(dictionary[csv][p]))
                outputFile.write(",")
            outputFile.write("\n")

writeFile(dictionaryEx)

这是输出,当我在Excel中打开它时显示格式正确:

,run2.csv,run1.csv,
 barium,,1,
 dieldrin,,4,
 enterococci,1,7,
 escherichia coli,14,,
 nickel,,3,
 ph,25,160,
 trichloroethylene,,1,

答案 1 :(得分:0)

类似,但更短

cols = dictionaryEx.keys()
rows = set()
for v in dictionaryEx.values():
    rows.update(v.keys()

with open('outputfile','w') as file:
    file.write(',' + ','.join(cols) + '\n')
    for r in sorted(rows):
        file.write(r + ",")
        file.write(",".join([str(d,get(r,"")) for d in dictionaryEx.values()]))
        file.write("\n")

应该在输出文件

中获取此信息
,run2.csv,run1.csv
 barium,,1
 dieldrin,,4
 enterococci,1,7
 escherichia coli,14,
 nickel,,3
 ph,25,160
 trichloroethylene,,1
相关问题