从fi创建列表字典

2024-05-14 07:55:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

如何将这些输入字典中,如下所示: dictionary={鞋款:[Nike,Addias,Puma,…] 裤子:[码头工人,李维斯….] 手表:【Timex、Tiesto……】 }在

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

我试过了

^{pr2}$

Tags: 文件txt列表names格式pantsothertimex
3条回答

这里有一个更简洁的方法来做事情,不过为了可读性你可能会想把它分开一点

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

相关问题 更多 >

    热门问题