Change dictionary values from int to string
<p>This is what my dictionary looks like.</p>

<pre><code>phoneBook = {"Skywalker": 55511243, "Solo": 55568711, "Vader": 55590858}
</code></pre>

<p>I need to change each phonenumber into a string and add <code>"+1-"</code> in front of it. But, I'm not sure how to do it.</p>

<p>With a simple dictionary comprehension:</p>

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

<p>Where <code>"+1-{}".format(v)</code> converts to a string and prepends <code>+1-</code> to it. Similarly you could use <code>"+1-" + str(v)</code> as noted in the other answer but I <em>personally</em> find it less readable.</p>

<pre><code>print(r)
{'Skywalker': '+1-55511243', 'Solo': '+1-55568711', 'Vader': '+1-55590858'}
</code></pre>

<p>Alternatively, if you want to do it <em>in-place</em>, i.e not create a new dictionary as comprehensions do, iterate <em>over the keys</em><sup>*</sup> and update the values:</p>

<pre><code>for k in phoneBook:
    phoneBook[k] = "+1-{}".format(phoneBook[k])
</code></pre>

<p><sup>*Iterating over the keys only is important, if you iterate over both keys and values you'll get odd behavior because you'll be altering the view you iterate through.</sup></p>

python string python-3.x dictionary int