Khan Shur
Khan Shur

Reputation: 19

Replacing a word that matches with a Key is not working in Python

So I am trying to replace a word that matches any of the keys in the dictionary by its values.

Below is the current code I have and my code is not replacing anything.

       for k, v in fdict.items():
           if word == k:
               word == v

So basically in the end I want the following to happen.

Upvotes: 0

Views: 42

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

You can simply do

for word in (jsondata['value']['segments'][i]['transcriptionData']['content']).split():
    word = fdict.get(word, word)

By using get, you are seeing if word is a valid key, if it is, return the associated value, otherwise, return the second argument as default, in this case word. You don't need to iterate through fdict, as that sort of defeats the purpose of the dictionary in the first place. Testing for membership is a time-constant process and fast.

If you want this to be reflected in the dictionary itself, you need to re-assign the value at that key:

# changing this to be more pythonic and readable
for segment in jsondata['value']['segments']:
    # assigning this to be a different variable for readability
    words = segment['transcriptionData']['content'].split()
    # join will make this a string again so we can re-assign it
    # to the key
    words = ' '.join(fdict.get(word, word) for word in words)

    # Now this will be reflected in your json
    segment['transcriptionData']['content'] = words

Furthermore, in your if statement, word==v will return False, as == is an equality test, not value assignment, and that should have been word = v

To address the update in the question, you never write your updated words anywhere. The data in your program is not the file, so any modifications made to the data will not be reflected in the file until you write the data back to the file.

# after you update words
# Note, this is a different file path, as w will truncate (wipe out) the 
# file if it exists, so use a different file path until you are sure your
# logic is sound
with open('somefile.json', 'w') as fh:
    json.dump(jsondata)

Upvotes: 1

Related Questions