anfwkdrn
anfwkdrn

Reputation: 297

(Python) converting a text file to a dictionary file

I have a text file like the one below

Apple, banana, milk, tomato, coffee
Stone, mountain, sky, wind
Blue, red, yellow, violet, green, gray
...

Can I load these text files and change them to dictionary format like below?

Dictionary = {
"Apple": random.choice(["banana", "milk", "tomato", "coffee"]),
"Stone": random.choice(["mountain", "sky", "wind"]),
"Blue": random.choice(["red", "yellow", "violet", "green", "grey"]),
...}

I have tried the code below, but I don't know how to add the element.

from collections import ChainMap   
import re
import random

with open('elemmmm.txt', 'rt', encoding='UTF8') as f:
    lli = [i.rstrip().split(', ') for i in f]

ii = []
i = 0
while i < len(lli):
    swaps = {(lli[i][0]): (lli[i][1:])}
    ii.append(swaps)
    i+=1

ewrr = dict(ChainMap(*ii))
print(ewrr)

>>>{'Apple': ['banana', 'milk', 'tomato', 'coffee'], 'Stone': ['mountain', 'sky', 'wind'], 'Blue': ['red', 'yellow', 'violet', 'green', 'grey']}

Upvotes: -1

Views: 88

Answers (1)

illusion
illusion

Reputation: 1301

You can try this:

import random

dict_ = {}
with open('test.txt', 'r') as f:
    lines = [i.rstrip().split(', ') for i in f]
    for li in lines:
        key = li.pop(0)
        dict_[key] = random.choice(li)

print(dict_)

Where dict_ contains your desired dict...

Upvotes: 2

Related Questions