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

3.3k Views Asked by At

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.

2

There are 2 best solutions below

3
On BEST ANSWER
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.

1
On
phonebook = {k: '0044-'+v for k,v in phonebook.items()}