ranger
ranger

Reputation: 63

Iterating and modifying a dictionary

I have code which has a dictionary of some words. The program intends to merge words.

That is if word i is in word j then merge the value of dictionary[word i] to dictionary[word j] and delete dictionary[word i]

for i in my_dict.keys():
   for j in my_dict.keys():
     if i!=j:
       if i in j:
          my_dict[j]+=my_dict[i]
          del my_dict[i]
       elif j in i:
          my_dict[i]+=my_dict[j]
          del my_dict[j]

Is this code valid?

Upvotes: 0

Views: 47

Answers (1)

cezar
cezar

Reputation: 12012

Your code is not valid. There is no command delete in python for removing elements from dictionary. It is called del. You can delete an item from dictionary like this:

del your_dictionary['some_key']

However that is not very pythonic. You can refactor your code like this:

for i in my_dict.keys():
    for j in my_dict.keys():
        if i != j:
            if i in j:
                my_dict[j] += my_dict.pop(i)
            elif j in i:
                my_dict[i] += my_dict.pop(j)

pop is a dictionary method, which returns and removes an item from the dictionary.

The above code is a suggestion only regarding the merging (concatenating) of the values in the dictionary. The double for loop still looks ugly. But first make it work, later you can improve the quality of the code. I hope my example can help you.

Upvotes: 1

Related Questions