Makaronen Makaronen - 11 months ago 47
Python Question

Change dictionary values from int to string

This is what my dictionary looks like.

phoneBook = {"Skywalker": 55511243, "Solo": 55568711, "Vader": 55590858}

I need to change each phonenumber into a string and add
in front of it. But, I'm not sure how to do it.

Answer Source

With a simple dict-comp:

r = {k: "+1-{}".format(v) for k,v in phoneBook.items()}

Where "+1-{}".format(v) converts to a string and prepends +1 to it.

{'Skywalker': '+1-55511243', 'Solo': '+1-55568711', 'Vader': '+1-55590858'}

If you want to do it in-place, i.e not create a new dictionary, iterate over the keys and update the values:

for k in phoneBook:
    phoneBook[k] = "+1-{}".format(phoneBook[k])