从文件中创建一个字典列表

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个回答

3

这里有一种更加简洁的方法来完成事情,但是为了可读性,您可能需要将其分解一下。

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

  1. 一个生成器表达式会更好一些。
  2. 遍历文件而不是分割(然后只需使用 line.rstrip())。否则,答案很好。
- nneonneo
你的意思是类似这样的代码吗:(line.rstrip().split(', ') for line in open('clothes.txt').readlines()) - Antimony

2

怎么样:

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

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'语句将确保在执行实现字典的代码后关闭文件读取器。从那里,您可以尽情使用字典!


毫无疑问,这个值可以很容易地存储到一个本地变量中,以去除冗余,但为了在这个示例中清晰明了,它被重复执行了两次。 - mikeybaby173

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))]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接