Replacing multiple occurrences in nested arrays

I have this python dictionary "mydict" containing arrays, here is what it looks like:

mydict = dict(
    one=['foo', 'bar', 'foobar', 'barfoo', 'example'], 
    two=['bar', 'example', 'foobar'], 
    three=['foo', 'example'])

I would like to replace all occurrences of "example" with "someotherword".

While I can already think of several ways to do this, is there a β€œpythonic” method for this?

+3
source share
3 answers
for arr in mydict.values():
    for i, s in enumerate(arr):
        if s == 'example':
            arr[i] = 'someotherword'
+2
source

If you want to leave the original untouched and just return the new dictionary with the changes made, you can use:

replacements = {'example' : 'someotherword'}

newdict = dict((k, [replacements.get(x,x) for x in v]) 
                for (k,v) in mydict.iteritems())

, , dictates dict. dict , :

for l in mydict.values():
    l[:]=[replacements.get(x,x) for x in l]

, , , . . , , .

+2

Here is another take:

for key, val in mydict.items():
    mydict[key] = ["someotherword" if x == "example" else x for x in val]

I found that string lists are very fast, but of course a profile if performance is important.

+1
source

Source: https://habr.com/ru/post/1699211/


All Articles