2012-10-23 49 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