Adding More Than One Value To Dictionary When Looping Through String
Solution 1:
This will solve all your problems:
def word_len_dict(my_string):
input_list = my_string.split(" ")
unique_set = set()
dictionary = {}
for item in input_list:
word = item.lower()
if word not in unique_set:
unique_set.add(word)
key = len(word)
if key not in dictionary:
dictionary[key] = []
dictionary[key].append(word)
return dictionary
You were wiping dict entries each time you encountered a new word. There were also some efficiencly problems (searching a list for membership while growing it resulted in an O(n**2) algorithm for an O(n) task). Replacing the list membership test with a set membership test corrected the efficiency problem.
It gives the correct output for your sample sentence:
>>> print(word_len_dict("The dogs run quickly forward to the park"))
{2: ['to'], 3: ['the', 'run'], 4: ['dogs', 'park'], 7: ['quickly', 'forward']}
I noticed some of the other posted solutions are failing to map words to lowercase and/or failing to remove duplicates, which you clearly wanted.
Solution 2:
you can create first the list of the unique words like this in order to avoid a first loop, and populate the dictionary on a second step.
unique_string = set("The dogs run quickly forward to the park".lower().split(" "))
dict = {}
for word in unique_string:
key, value = len(word), word
if key notindict: # or dict.keys() for better readability (but is the same)dict[key] = [value]
else:
dict[key].append(value)
print(dict)
Solution 3:
You are assigning an empty list to the dictionary item before you append the latest word, which erases all previous words.
Solution 4:
for word in unique_list:
dictionary[len(word)] = [x for x in input_list if len(x) == len(word)]
Solution 5:
Your code is simply resetting the key to an empty list each time, which is why you only get one value (the last value) in the list for each key.
To make sure there are no duplicates, you can set the default value of a key to a set which is a collection that enforces uniqueness (in other words, there can be no duplicates in a set).
defword_len_dict(my_string):
dictionary = {}
input_list = my_string.split(" ")
for word in input_list:
iflen(word) notin dictionary:
dictionary[len(word)] = set()
dictionary[len(word)].add(word.lower())
return dictionary
Once you add that check, you can get rid of the first loop as well. Now it will work as expected.
You can also optimize the code further, by using the setdefault
method of dictionaries.
for word in input_list:
dictionary.setdefault(len(word), set()).add(word.lower())
Post a Comment for "Adding More Than One Value To Dictionary When Looping Through String"