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 ?

3 Answers 3

2
for arr in mydict.values():
    for i, s in enumerate(arr):
        if s == 'example':
            arr[i] = 'someotherword'
Sign up to request clarification or add additional context in comments.

1 Comment

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.)
2

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.

Comments

1

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.

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.