[英]Tips formatting dictionary with sub-dictionaries into a table
我正在为 class 开发一个项目,该项目基本上允许用户输入字符串,然后标记它们以制作图表。 例如,用户将输入标签类别,如 colors、大小和纹理。 然后这些类别有红色,黄色蓝色等子类别。 然后他们输入项目名称以将它们分类到每个类别的子类别中。 下面是我的意思的一个例子。
rockdictionary = {
'colors' : {
'red' : ['thing1', 'thing 4'],
'blue' : ['thing 2', 'thing 3'],
'yellow' :['thing 5']
},
'texture': {
'smooth' : ['thing 5', 'thing 3'],
'rough' : ['thing1'],
'bumpy' :['thing4', 'thing 2']},
'size' : {
'small' : ['thing 2', 'thing 4', 'thing 3'] ,
'medium': [],
'large':['thing 1', 'thing 5']
}
}
我想出了如何获得一个看起来像示例的字典,但我不知道如何将其格式化为如下图所示的图表
物品 | 颜色 | 尺寸 | 质地 |
---|---|---|---|
东西1 | 红色的 | 小的 | 光滑的 |
东西2 | 蓝色的 | 大的 | 起疙瘩的 |
这是我到目前为止所得到的:
userwidth = int(input('How wide would you like your columns to be? '))
for key in categories:
tableformat1 = '{header:>{width}}'.format(header=key, width=userwidth)
tableformat2 = '{header:>{width}}'.format(header=key, width=(userwidth*2))
categorylist = list(categories)
if key != categorylist[-1]:
print(tableformat1.format(header=key), end = '|')
elif key == categorylist[0]:
print(tableformat2.format(header=key, width=userwidth))
else:
print(tableformat1.format(header=key))
print('-' * (len(categories) * userwidth))
for name in itemnames:
column1format = '{item:{width}}'.format(item=name, width=userwidth)
print(column1format.format(item=name, end = '|'))
print('-' * userwidth)
这给了我:
一个| 乙| C
3
老实说,我不太确定 go 从这里到哪里。 任何帮助将不胜感激。 有关完整代码,请参见此处: https://pastebin.com/WSKcDEvx
在 2 级字典中重构数据: [thing_name][category] = value
和一些 pandas 以获得不错的 output
{
"thing 1": {"colors": "red","texture": "rough","size": "large"},
"thing 4": {"colors": "red","texture": "bumpy","size": "small"},
...
}
import pandas as pd
rockdictionary = {
'colors': {'red': ['thing 1', 'thing 4'], 'blue': ['thing 2', 'thing 3'], 'yellow': ['thing 5']},
'texture': {'smooth': ['thing 5', 'thing 3'], 'rough': ['thing 1'], 'bumpy': ['thing 4', 'thing 2']},
'size': {'small': ['thing 2', 'thing 4', 'thing 3'], 'medium': [], 'large': ['thing 1', 'thing 5']}
}
items = defaultdict(dict)
for category, others in rockdictionary.items():
for value, things in others.items():
for thing in things:
items[thing][category] = value
df = pd.DataFrame(items).T.fillna("").sort_index()
print(df)
print(df.to_markdown())
colors texture size
thing 1 red rough large
thing 2 blue bumpy small
thing 3 blue smooth small
thing 4 red bumpy small
thing 5 yellow smooth large
colors | 质地 | 尺寸 | |
---|---|---|---|
事情 1 | 红色的 | 粗糙的 | 大的 |
事情 2 | 蓝色的 | 起疙瘩的 | 小的 |
事情 3 | 蓝色的 | 光滑的 | 小的 |
事情 4 | 红色的 | 起疙瘩的 | 小的 |
事情 5 | 黄色 | 光滑的 | 大的 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.