Replacing multiple occurrences in nested arrays


Replacing multiple occurrences in nested arrays



I've got this python dictionary "mydict", containing arrays, here's what it looks like :

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

i'd like to replace all the occurrences of "example" by "someotherword".

While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?




Multidimensional arrays using integers and strings

1:



how to convert a value type to byte[] in C#?
for arr in mydict.values():     for i, s in enumerate(arr):         if s == 'example':             arr[i] = 'someotherword' 


How to find if a number is contained in an array of number ranges in java


PHP in_array not working

2:



Assign array of pointers to array
If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use:.
In C - check if a char exists in a char array
replacements = {'example' : 'someotherword'}  newdict = dict((k, [replacements.get(x,x) for x in v])                  for (k,v) in mydict.iteritems()) 
This also has the advantage that its easy to extend with new words just by adding them to the replacements dict.


Java creating byte array whose size is represented by a long
If you want to mutate an existing dict in place, you can use the same approach:.
Passing pointers of arrays in C
for l in mydict.values():     l[:]=[replacements.get(x,x) for x in l] 
However it's probably going to be slower than J.F Sebastian's solution, as it rebuilds the whole list rather than just modifying the changed elements in place..


3:


Here's another take:.
for key, val in mydict.items():     mydict[key] = ["someotherword" if x == "example" else x for x in val] 
I've found that building lists is very fast, but of course profile if performance is important..



82 out of 100 based on 42 user ratings 1042 reviews