Search code examples
pythonfor-loopdictionaryprefix

How to add a prefix to each value in a dictionary, using a loop?


I've been given the following dictionary:

phonebook = {'Tom': '0545345345367',
             'John': '0764345323434',
             'Sandy': '0235452342465',
             'Ewan': '0656875345234',
             'Andy': '0673423123454',
             'Rebecca': '0656875345234',
             'Vicky': '0456740034344',
             'Gary': '0656875345234'}

And the problem asks me to add the prefix '0044-' before each phone number by using a for loop. I've tried to research it but everything I find seems far too complex for a problem like this.


Solution

  • for k in phonebook:
        phonebook[k] = '0044-' + phonebook[k]
    

    I dislike the "mutation in place while iterating" approach.

    But in this particular case it's safe (no keys are inserted or deleted). Iterate over phonebook.keys() if you want to always be safe.