views:

316

answers:

3

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 ?

+2  A: 
for arr in mydict.values():
    for i, s in enumerate(arr):
        if s == 'example':
            arr[i] = 'someotherword'
J.F. Sebastian
The question is subjective, therefore it should not have an accepted answer. The code above is the simplest code I could think of for the *specific* task at hand but I would not call the most "pythonic" one (One might use different priorities for the task and it would lead to a different code.)
J.F. Sebastian
+2  A: 

If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use:

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. If you want to mutate an existing dict in place, you can use the same approach:

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.

Brian
+1  A: 

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.

Ryan Ginstrom