Home > Software engineering >  How to convert a file with words on different newlines into a dictionary based on values each word h
How to convert a file with words on different newlines into a dictionary based on values each word h

Time:01-20

I am trying to convert a file, where every word is on a different newline, into a dictionary where the keys are the word sizes and values are the lists of words.

The first part of my code has removed the newline characters from the text file, and now I am trying to organize the dictionary based on the values a word has.

with open(dictionary_file, 'r') as file:
    wordlist = file.readlines()
    print([k.rstrip('\n') for k in wordlist])
    dictionary = {}
    for line in file:
        (key, val) = line.split()
        dictionary[int(key)] = val
    print(dictionary)

However, I keep getting the error that there aren't enough values to unpack, even though I'm sure I have already removed the newline characters from the original text file. Another error I get is that it will only print out the words in a dictionary without the newlines, however, they aren't organized by value. Any help would be appreciated, thanks! :)

(key, val) = line.split()
    ^^^^^^^^^^
ValueError: not enough values to unpack (expected 2, got 1)

CodePudding user response:

I'm not sure why you're trying to use line.split(). All you need is the length of the word, so you can use the len() function. Also, you use collections.defaultdict to make this code shorter. Like this:

import collections


words = collections.defaultdict(list)
with open('test.txt') as file:
    for line in file:
        word = line.strip()
        words[len(word)].append(word)

CodePudding user response:

try this

with open(dictionary_file, 'r') as file:
    dictionary = {}
    for line in file:
        val = line.strip().split()
        dictionary[len(val)] = val
    print(dictionary)
  • Related