Reputation: 11
Okay so I have a program I'm writing in python, and it contains a dictionary. The dictiionary as of now looks like:
phoneList = {'Tom':'564-0000','Sue':'564-0000','Roberto':'564-0000'}
How would I go about adding the same area code to each of the key values. As of now this is what I've com up with, but I can't seem to get it to do what I want.
import copy
def main():
phoneList = {'Tom':'564-0000','Sue':'564-0000','Roberto':'564-0000'}
newDict = newDictWithAreaCodes(phoneList)
#print(newDict)
def newDictWithAreaCodes(phoneBook):
updatedDict = copy.copy(phoneBook)
newStr = "518-"
keyList = phoneBook.keys()
for key in keyList:
del updatedDict[key]
newKey = newStr + key
updatedDict[key] = newKey
print(updatedDict)
Upvotes: 1
Views: 122
Reputation: 10370
phoneList = {'Tom':'564-0000','Sue':'564-0000','Roberto':'564-0000'}
for key in phoneList:
phoneList[key] = '518-' + phoneList[key]
produces:
{'Roberto': '518-564-0000', 'Sue': '518-564-0000', 'Tom': '518-564-0000'}
Upvotes: 0
Reputation: 25974
Pretty straightforward with a comprehension:
{k:'{}-{}'.format(518,v) for k,v in phoneList.items()}
Out[56]: {'Roberto': '518-564-0000', 'Sue': '518-564-0000', 'Tom': '518-564-0000'}
And if I were to write that as a function:
def prepend_area_code(d, code = 518):
'''Takes input dict *d* and prepends the area code to every value'''
return {k:'{}-{}'.format(code,v) for k,v in d.items()}
Random comments:
phoneList
is a dict
, don't call it a list
. phone_list
, methods: new_dict_with_area_codes
, etc.Upvotes: 2
Reputation: 12092
I think you are confused with dictionary keys and values. Doing phoneBook.keys()
gives you a list of keys in your phoneBook
dictionary namely Tom, Roberto and Sue
. phoneBook[key]
gives the corresponding values.
I think you mean to concatenate '518' to the values of the keys? Your code concatenates the key to the value. You change this line in your code:
newKey = newStr + key
to:
newKey = newStr + phoneBook[key]
This will give you what you want, when you print updatedDict
:
{'Sue': '518-564-0000', 'Roberto': '518-564-0000', 'Tom': '518-564-0000'}
You can achieve the same using dictionary comprehension like this:
>>> phoneList = {'Tom':'564-0000','Sue':'564-0000','Roberto':'564-0000'}
>>> newDict = {k: '518-' + v for k, v in phoneList.items()}
>>> newDict
{'Sue': '518-564-0000', 'Roberto': '518-564-0000', 'Tom': '518-564-0000'}
Upvotes: 0
Reputation: 86366
Is this what you are looking for?
area_code = '567'
phoneList = {'Tom':'564-0000','Sue':'564-0000','Roberto':'564-0000'}
phoneList = {k : '-'.join((area_code, v)) for k, v in phoneList.iteritems()}
Result:
>>> phoneList
{'Sue': '567-564-0000', 'Roberto': '567-564-0000', 'Tom': '567-564-0000'}
Upvotes: 0