【发布时间】:2021-06-19 01:49:15
【问题描述】:
我有这个文本文件,其中包含某些产品,每个产品都有可用的商店。商店行以 tab 字符开头,而产品行则没有。
为了能够以更好的方式对其进行可视化,我想将其作为字典进行排序,将商店名称作为键,然后是产品列表。一个例子是:
{
'Store1' : ['product1', 'product2'],
'Store2' : ...
}
这是我拥有的数据示例,为每个产品存储:
- Crucial Ballistix BLT8G4D26BFT4K
- Infor-Ingen
- 毕普
- 电脑厂
- 我的盒子
- 爱国者签名线PSD48G266681
- PC 快递
- Soluservi
- 金士顿KCP426NS6/8
- 优科技
- 毕普
预期的输出必须是这样的(打印得很漂亮):
{
'Infor-Ingen' : ['Crucial Ballistix BLT8G4D26BFT4K' ],
'Bip' : ['Crucial Ballistix BLT8G4D26BFT4K',
'Kingston KCP426NS6/8' ],
'PC Factory' : ['Crucial Ballistix BLT8G4D26BFT4K' ],
'MyBox' : ['Crucial Ballistix BLT8G4D26BFT4K' ],
'PC Express' : ['Patriot Signature Line PSD48G266681' ],
'Soluservi' : ['Patriot Signature Line PSD48G266681' ],
'YouTech' : ['Kingston KCP426NS6/8' ]
}
我有这个代码
from collections import OrderedDict
od = OrderedDict()
tienda, producto ,otra,aux,wea= [], [],[], [],[]
with open("rams.txt","r") as f:
data = f.readlines()
for linea in data:
linea = linea.strip('\n')
if '\t' in linea:
tienda.append(linea.strip('\t'))
aux.append(linea.strip("\t").strip("\n"))
else:
otra.append(aux)
aux=[]
producto.append(linea)
aux.append(linea.strip("\n"))
tienda = sorted(list(set(tienda)))
for i in range(1,len(otra)):
wea=[]
for key in tienda:
if key in otra[i]:
wea.append(otra[i][0])
od[key] = wea
现在的问题是,在打印字典时,它给了我这样的信息:
('Bip', ['Crucial Ballistix BLT8G4D26BFT4K ']), ('Infor-Ingen', ['Crucial Ballistix BLT2K8G4D26BFT4K ']), ('MyBox', ['Crucial Ballistix CT16G4DFD8266']),..)
【问题讨论】:
标签: python dictionary