我有一个用python写的程序,里面有一个字典。目前的措辞如下:
phoneList = {'Tom':'564-0000','Sue':'564-0000','Roberto':'564-0000'}
我将如何向每个键值添加相同的区号。到目前为止,这是我一直想做的,但我似乎不能让它做我想做的事。你知道吗
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)
我认为你被字典的键和值弄糊涂了。执行
phoneBook.keys()
将为您提供phoneBook
字典中的键列表,即Tom, Roberto and Sue
。phoneBook[key]
给出相应的值。你知道吗我想你的意思是把“518”和键的值连接起来?代码将键连接到值。在代码中更改此行:
收件人:
当您打印
updatedDict
时,这将提供您想要的:使用字典理解可以达到同样的效果,如下所示:
这就是你要找的吗?你知道吗
结果:
非常直截了当的理解:
如果我把它写成一个函数:
随机评论:
phoneList
是dict
,不要叫它list
。你知道吗phone_list
,方法:new_dict_with_area_codes
,等等,遵循python命名约定相关问题 更多 >
编程相关推荐