2017-07-06 2 views
0

私は私が唯一のウェブサイトのテキストからなるCSVファイルを持っている瞬間に、しかしPythonで複数のリストを作成するにはどうすればいいですか?

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

、次のような構造を持っているdictsのリストを作りたいです。

以下私はどういうわけか私のウェブサイトのテキストファイルと同じ長さのリストを作成してから、それらを圧縮して、そこから辞書を作成しようとしました。私はここで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ファイルの入力は、記述されているように1行に1文字列であり、質問に。より具体的な例を意味しますか? – 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) 

私はtは私がよく理解場合は

関連する問題