好的,我有一个程序我用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)
答案 0 :(得分:2)
理解非常简单:
{k:'{}-{}'.format(518,v) for k,v in phoneList.items()}
Out[56]: {'Roberto': '518-564-0000', 'Sue': '518-564-0000', 'Tom': '518-564-0000'}
如果我把它写成一个函数:
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()}
随机评论:
phoneList
是dict
,请勿将其称为list
。 phone_list
,方法:new_dict_with_area_codes
等。答案 1 :(得分:0)
这是你在找什么?
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()}
结果:
>>> phoneList
{'Sue': '567-564-0000', 'Roberto': '567-564-0000', 'Tom': '567-564-0000'}
答案 2 :(得分:0)
我认为你对字典键和值感到困惑。执行phoneBook.keys()
会为您提供phoneBook
字典中的密钥列表Tom, Roberto and Sue
。 phoneBook[key]
给出相应的值。
我认为你的意思是将'518'连接到键的值?您的代码将键连接到值。您在代码中更改了这一行:
newKey = newStr + key
为:
newKey = newStr + phoneBook[key]
当您打印updatedDict
:
{'Sue': '518-564-0000', 'Roberto': '518-564-0000', 'Tom': '518-564-0000'}
你可以使用这样的词典理解来实现同样的目标:
>>> 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'}
答案 3 :(得分:0)
phoneList = {'Tom':'564-0000','Sue':'564-0000','Roberto':'564-0000'}
for key in phoneList:
phoneList[key] = '518-' + phoneList[key]
产生
{'Roberto': '518-564-0000', 'Sue': '518-564-0000', 'Tom': '518-564-0000'}