3

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

4 Answers 4

1

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.']}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried the code and got "AttributeError: 'int' object has no attribute 'replace'" I tried to convert to string with str ......final_d = { k: [item.replace(k, k[:2]+"...") for str(item) in v] for k, v in d.items()} and it stalled. final_d = { k: [str(item.replace(k, k[:2]+"...")) for item in v] for k, v in d.items()} and got the same error
@JohnAiton - The code above does not throw an exception for the dictionary as posted in question. No need to convert item to string - it is already a string (and that is also not correct syntax). Also the second code you posted in the comment runs fine)
1

You can use regex like below:

import re

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

{k : [re.sub(fr'\b{k}\b',  f'{k[:2]}...', s)   for s in v] for k,v in d.items()}

Output

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

1 Comment

This would also replace firmly with fi...ly if the key is firm.
0
  • for word in v: goes by whole sentences; to get word by word, we need to either:
    • use for sentence in v: then for word in sentence.split(); or
    • use for sentence in v: then if k in sentence
  • To assign it back, we need to replace or assign into the list; to get the index to assign into the array, we can use for i, sentence in enumerate(v) then later v[i] = final_sentence

In general, be careful about modifying the dictionary while you're iterating over it; changing an existing entry should be fine, but anything else can mess up the iteration. If you need to make more extensive changes, build a new dictionary with the result (or build a list of changes to apply, then do that in a separate loop).

5 Comments

Note that v is a list of strings, so need to nest loops another level.
Right; I missed that...
I did have v.split(' ') before but it gave me AttributeError: 'list' object has no attribute 'split' when I just tried v.split() it gave me the same AttributeError
Yeah, as pointed out in the first comment, we need to nest the loops another level
Answer updated.
0

Assuming the values for your dictionary will always be a list containing a single string (your sentence). You could use the code below:

d = {key:[value[0].replace(key, key[:2] + "...")] for key, value in d.items()}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.