2012-10-23 52 views
3

我有一個txt文件的格式如下列表:創建列表的字典文件

Shoes, Nike, Addias, Puma,...other brand names 
Pants, Dockers, Levis,...other brand names 
Watches, Timex, Tiesto,...other brand names 

如何把這些變成字典這樣的格式: 詞典= {鞋:耐克, Addias,彪馬,.....] 褲子:[碼頭工人,李維斯.....] 腕錶:[天美時,鐵斯托,.....] }

如何做到這一點的一個循環而不是手動輸入。

我曾嘗試

 clothes=open('clothes.txt').readlines() 
     clothing=[] 
     stuff=[] 
     for line in clothes: 
       items=line.replace("\n","").split(',') 
       clothing.append(items[0]) 
       stuff.append(items[1:]) 



    Clothing:{} 
     for d in clothing: 
      Clothing[d]= [f for f in stuff] 

回答

2

如何:

file = open('clothes.txt') 
clothing = {} 
for line in file: 
    items = [item.strip() for item in line.split(",")] 
    clothing[items[0]] = items[1:] 
3

這裏的做事更簡潔的方式,雖然你可能會想有點分裂的可讀性

wordlines = [line.split(', ') for line in open('clothes.txt').read().split('\n')] 
d = {w[0]:w[1:] for w in wordlines} 
+0

1)genexpr會更好一些,2)迭代文件而不是分割(然後是'line.rstrip()')。否則,很好的答案。 – nneonneo

+0

你的意思是類似'(line.rstrip()。split(',')for line in open('clothes.txt')。readlines())'? – Antimony

+0

是的,除了你可以離開'.readlines'。 – nneonneo

0

使用列表理解你可以做:

clothes=[line.strip() for line in open('clothes.txt').readlines()] 
clothingDict = {} 
for line in clothes: 
    arr = line.split(",") 
    clothingDict[arr[0]] = [arr[i] for i in range(1,len(arr))] 
1

試試這個,它會刪除需要更換換行,是相當簡單的,但有效:

clothes = {} 
with open('clothes.txt', 'r', newline = '/r/n') as clothesfile: 
    for line in clothesfile: 
     key = line.split(',')[0] 
     value = line.split(',')[1:] 
     clothes[key] = value 

的with語句將確保該文件閱讀器關閉後您的代碼來實現該字典被執行。從那裏你可以使用字典到你心中的內容!

+1

你不應該執行'line.split'兩次...... – nneonneo

+0

當然是真的;它可以很容易地被存儲到一個局部變量中去除冗餘,但是爲了清楚起見,在這個例子中它做了兩次。 – mikeybaby173