我想从存储在字典中的数据创建一个2D表格格式。
示例:
d = {'ID1':[('Experiment1', 40), (Experiment2, 59), (Experiment3, 65)],
'ID2':[('Experiment1', 68), (Experiment2, 21), (Experiment3, 39)],
'ID3':[('Experiment1', 57), (Experiment2, 15), (Experiment4, 99)]}应提供下表:
Experiment1 Experiment2 Experiment3 Experiment4ID1 ...40................................59...............................65................................'‘
ID2....68...............................21................................39................................'‘
ID3....57...............................15................................''..................................99
其中IDx是行标签,而Experimentx是列名。如果数据集的列名没有值,则应添加一个空字符串作为占位符。
有没有人能帮我解决这个问题呢?在python中有没有现成的格式,我可以使用?
发布于 2011-09-14 18:14:05
一个又快又脏的实现(修复问题中的拼写错误...)
d = {'ID1':[('Experiment1', 40), ('Experiment2', 59), ('Experiment3', 65)],
'ID2':[('Experiment1', 68), ('Experiment2', 21), ('Experiment3', 39)],
'ID3':[('Experiment1', 57), ('Experiment2', 15), ('Experiment4', 99)]}
COLUMN_WIDTH = 20
STRING_WHEN_MISSING = '""'
PADDING_STRING = "."
#first determine what are the columns - from the first line
columns = ["id"] #there is always at least the id column
columns = columns + [colName for (colName, colValue) in d.items()[0][1]]
print "".join([ col.ljust(COLUMN_WIDTH) for col in columns])
#browse the lines, order by ID Ascending
for (rowId, rowValues) in sorted(d.items(), key= lambda x: x[0].lower()):
#print rowId
#print rowValues
rowValuesDict = dict(rowValues) #make it a dict with access by key
rowValuesDict["id"] = rowId
#print rowValuesDict
print "".join([ str(rowValuesDict.get(col, STRING_WHEN_MISSING)).ljust(COLUMN_WIDTH, PADDING_STRING) for col in columns])这将打印出来:
id Experiment1 Experiment2 Experiment3
ID1.................40..................59..................65..................
ID2.................68..................21..................39..................
ID3.................57..................15..................""..................注意:
你的原始字典的格式有点奇怪...我希望会有更多这样的东西:
d = [('ID1',{'Experiment1': 40, 'Experiment2':59, 'Experiment3':65}),
('ID2',{'Experiment1': 68, 'Experiment2':21, 'Experiment3':39})] 一些评论:
对于这类事情,您需要了解一些Python字符串方法:center(), ljust() and rjust(),它们在字符串之前和/或之后添加字符,以强制字符串的总宽度。
除此之外,这个想法主要是关于循环遍历列表/字典并提取值。
注意,当给定的键不存在值时,可以使用dict方法get(),该方法允许使用默认值。
https://stackoverflow.com/questions/7414226
复制相似问题