如何在python中制作多个列表的dict?

时间:2017-07-06 12:50:55

标签: python csv dictionary list-comprehension

我想列出具有以下结构的词典

[{'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)))

我很清楚尝试的丑陋......

3 个答案:

答案 0 :(得分:2)

由于唯一的区别是文本,您可以执行以下操作:

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

每个字典的'Business':'Attorney'对都是相同的,而与'Website text'对应的值将是您文件中的数据。

答案 1 :(得分: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)

答案 2 :(得分:0)

这就是我要做的事情:

data = []

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

我不知道我是否理解你想做什么