简体   繁体   English

从文件创建列表字典

[英]Creating a dictionary of lists from a file

I have a list in the following format in a txt file : 我在txt文件中有以下格式的列表:

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

how to put these into dictionary like this format: dictionary={Shoes: [Nike, Addias, Puma,.....] Pants: [Dockers, Levis.....] Watches:[Timex, Tiesto,.....] } 如何将这些放入字典中,如下格式:字典= {鞋子:[Nike,Addias,Puma,.....]裤子:[Dockers,Levis .....]手表:[Timex,Tiesto,... ..]}

How to do this in a for loop rather than manual input. 如何在for循环而不是手动输入中执行此操作。

i have tried 我试过了

       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]

Here's a more concise way to do things, though you'll probably want to split it up a bit for readability 这里有一个更简洁的方法,虽然你可能想要将它分开以便于阅读

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

How about: 怎么样:

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

Try this, it will remove the need for replacing line breaks and is quite simple, but effective: 试试这个,它将不再需要替换换行符,而且很简单,但有效:

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

The 'with' statement will make sure the file reader is closed after your code to implement the dictionary is executed. 'with'语句将确保在执行实现字典的代码后关闭文件阅读器。 From there you can use the dictionary to your heart's content! 从那里你可以使用字典到你的内心!

Using list comprehension you could do: 使用列表理解你可以做到:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM