繁体   English   中英

从文件创建列表字典

[英]Creating a dictionary of lists from a file

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

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

如何将这些放入字典中,如下格式:字典= {鞋子:[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]

这里有一个更简洁的方法,虽然你可能想要将它分开以便于阅读

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

怎么样:

file = open('clothes.txt')
clothing = {}
for line in file:
    items = [item.strip() for item in line.split(",")]
    clothing[items[0]] = items[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'语句将确保在执行实现字典的代码后关闭文件阅读器。 从那里你可以使用字典到你的内心!

使用列表理解你可以做到:

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