2017-07-06 66 views
0

我想使具有下列结构类型的字典列表,如何在python中制作多个列表的字典?

[{'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, {'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, ...] 

然而此刻我只有由该网站文字的csv文件。

下面我试图以某种方式创建与我的网站文本文件相同长度的列表,然后压缩它们并从中创建一个字典。当涉及到从2个列表创建一个字典时,我一直无法找到有关这里的信息。

with open('attorneys text.csv') as data_file: 
    attorneys = list(line for line in data_file) 

website = [] 
business = [] 
classes = [] 
for l in range(len(attorneys)): 
    website.append("Website text") 

for k in range(len(attorneys)): 
    business.append("Business") 

for i in range(len(attorneys)): 
    classes.append("Attorney") 

data = dict(zip((business, classes, website, attorneys))) 

我非常清楚的尝试,以及对丑陋的...

+0

你应该分享CSV文件的输入和预期输出的一个小例子很好的东西。我看到很多需要改进的空间,但是这看起来更像是codereview的问题...... –

+0

@ Jean-FrançoisFabrecsv文件的输入只是每行描述的一个字符串,并且所需的输出是首先显示的字符串在问题中。你的意思是一个更具体的例子吗? – briyan

回答

2

由于唯一的区别是文本,你可以做以下:

with open('attorneys text.csv') as data_file: 
    data = [{'Business':'Attorney', 'Website text':line} for line in data_file] 

'Business':'Attorney'对对于每个字典都是相同的,wh ile与'Website text'对应的值将是来自文件的数据。

+0

它工作,我接受。谢谢! – briyan

0

您可以使用defaultdict

from collections import defaultdict 
s = ["Business", "Attorney", "Website text"] 
data = defaultdict(list) 

data[s[0]].append(business) 
data[s[1]].append(classes) 
data[s[2]].append(website) 
+0

不太清楚这是如何解决它? – briyan

0

这是我会做:

data = [] 

with open('attorneys text.csv') as data_file: 
    for line in data_file 
    row = { "Business": "Attorney", "Website text": line} 
    data.append(row) 

我不知道如果我理解你想要做