Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use python to loop through values in dictionary to change value based on key

I have a dictionary with 100 entries like this..

d = {
    'entrenched': ['the Internet is firmly entrenched in our lives.'], 
    'profoundly': ['racism is profoundly entrenched within different social spheres.']
}

I want to loop through the dictionary and replace one of the words in the value based on the key.

The output should look like this:

d = {
    'entrenched': ['the Internet is firmly en...   in our lives.'], 
    'profoundly': ['racism is pr...   entrenched within different social spheres.']
}

I tried this code

for k,v in d.items():    
    for word in v:
        if word == k:
            gapped_word = word[1:]+ '...'
            final_sentence = v.replace(word,gapped_word )
            print(final_sentence)

but got no output. I'm also not sure what the final line should be if instead of printing I am replacing the original value with the adjusted one

like image 257
John Aiton Avatar asked Mar 28 '26 19:03

John Aiton


1 Answers

As each dictionary item maps from a string to a list you should iterate the items in that list. Then, for each of those items, perform the replacing. In addition, notice that you do not have to split the sentence into words, but simply perform the operation over the entire sentence.

final_d = { k: [item.replace(k, k[:2]+"...") for item in v] for k, v in d.items()}

Where the value of final_d is are desired:

{'entrenched': ['the Internet is firmly en... in our lives.'],
 'profoundly': ['racism is pr... entrenched within different social spheres.']}
like image 194
Gilad Green Avatar answered Mar 30 '26 11:03

Gilad Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!