3

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

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

如何将这些放入字典中,如下所示:dictionary={Shoes: [Nike, Addias, Puma,.....] Pants: [Dockers, Levis.....] Watches:[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

4 回答 4

3

这是一种更简洁的做事方式,尽管您可能希望将其拆分一下以提高可读性

wordlines = [line.split(', ') for line in open('clothes.txt').read().split('\n')]
d = {w[0]:w[1:] for w in wordlines}
于 2012-10-23T05:21:23.810 回答
2

怎么样:

file = open('clothes.txt')
clothing = {}
for line in file:
    items = [item.strip() for item in line.split(",")]
    clothing[items[0]] = items[1:] 
于 2012-10-23T05:19:59.340 回答
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' 语句将确保在执行实现字典的代码后关闭文件读取器。从那里您可以随心所欲地使用字典!

于 2012-10-23T06:33:41.797 回答
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))]
于 2012-10-23T05:23:07.080 回答