Makaronen Makaronen - 2 months ago 6
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
"+1-"
in front of it. But, I'm not sure how to do it.

Answer

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.

print(r)
{'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])
Comments