-2

I am writing a program to create a dictionary in python were the key will be the lenghth of words and the value will be the words itself. So therefore, if i have say a word like "in" and "to", i expect the dictionary to print dict_value = {2:["in","to"]}. To further clarify my problem here is my code:

string_value = "I ate a bowl of cereal out of a dog bowl today."
remove_p = string_value.replace(".","")
remove_c = remove_p.replace(",","")
remove_q = remove_c.replace("?","")
remove_e = remove_q.replace("!","")
remove_a = remove_e.replace('\'',"")
lowervalue = remove_a.lower()
split_v = lowervalue.split()
length = {}
for i in split_v:  
   length[len(i)] = []
   length[len(i)].append(i)         
print length

This is what my code is printing:

{1: ['a'], 2: ['of'], 3: ['dog'], 4: ['bowl'], 5: ['today'], 6: ['cereal']}

This is what i want it to print:

{1: ['i', 'a', 'a'], 2: ['of', 'of'], 3: ['ate', 'out', 'dog'], 4: ['bowl', 'bowl'], 5: ['today'], 6: ['cereal']}

So, if a word has the same length it should be printed under the same keys. Thanks for your help in advance. This question is about displaying words with the same length under one key and does not involve refactoring. I have reviewed similar questions but no perfect fit for mine. They are either too advanced or too basic

user8964866
  • 61
  • 1
  • 7
  • 5
    Possible duplicate of [python dictionary and default values](https://stackoverflow.com/questions/9358983/python-dictionary-and-default-values) – Nir Alfasi Nov 19 '17 at 04:14
  • By doing `length[len(i)] = []` you're overriding existing results. Lookup: [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) – Nir Alfasi Nov 19 '17 at 04:15

2 Answers2

0

You can replace your length[len(i)] = [] with an if statement to prevent it from being executed on every execution of the loop:

   if len(i) not in length.keys():
       length[len(i)] = []

Not very efficient, but a simple answer.

John Anderson
  • 35,991
  • 4
  • 13
  • 36
0

There is a pattern for this type of problem:

Let's solve your issue in two steps:

first split() the string:

for item in string_value.split():

Second step just follow this pattern:

for item in string_value.split():
    if len(item) not in final_dict:
        final_dict[len(item)]=[item]
    else:
        final_dict[len(item)].append(item)

Final code:

string_value = "I ate a bowl of cereal out of a dog bowl today."
final_dict={}
for item in string_value.split():
    if len(item) not in final_dict:
        final_dict[len(item)]=[item]
    else:
        final_dict[len(item)].append(item)

print(final_dict)

output:

{1: ['I', 'a', 'a'], 2: ['of', 'of'], 3: ['ate', 'out', 'dog'], 4: ['bowl', 'bowl'], 6: ['cereal', 'today.']}

if we have :

string_value = "I ate a bowl of cereal out of a dog bowl today."
from collections import defaultdict

new_dict=defaultdict(list)

then one line apporach:

[new_dict[len(item)].append(item) for item in string_value.split()]
print(new_dict)
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88