user1753878
user1753878

Reputation: 109

Creating a dictionary of lists from a file

I have a list in the following format in a txt file :

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,.....] }

How to do this in a for loop rather than manual input.

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]

Upvotes: 3

Views: 173

Answers (4)

mikeybaby173
mikeybaby173

Reputation: 1312

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. From there you can use the dictionary to your heart's content!

Upvotes: 1

emschorsch
emschorsch

Reputation: 1669

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

Upvotes: 0

Bi Rico
Bi Rico

Reputation: 25833

How about:

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

Upvotes: 2

Antimony
Antimony

Reputation: 39491

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}

Upvotes: 3

Related Questions