从文件创建列表字典

时间:2012-10-23 05:16:38

标签: python list dictionary

我在txt文件中有以下格式的列表:

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

如何将这些格式化为字典:      dictionary = {鞋子:[Nike,Addias,Puma,.....]                  裤子:[Dockers,Levis .....]                  手表:[Timex,Tiesto,.....]                  }

如何在for循环而不是手动输入中执行此操作。

我试过了

       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]

4 个答案:

答案 0 :(得分:3)

这是一种更简洁的做事方式,尽管你可能想要将其拆分以便于阅读

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

答案 1 :(得分:2)

怎么样:

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

答案 2 :(得分: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'语句将确保在执行实现字典的代码后关闭文件阅读器。从那里你可以使用字典到你的内心!

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