如何在python字典中追加键的值?

如何在python字典中追加键的值?,python,dictionary,key,Python,Dictionary,Key,好的,我有一个用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

好的,我有一个用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) 

这就是你要找的吗

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'}

非常直截了当的理解:

{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
    ,不要称之为
    列表
  • 另外,遵循python变量命名约定:
    phone\u list
    ,方法:
    new\u dict\u with\u area\u code
    ,等等

我认为您被字典键和值弄糊涂了。执行
phoneBook.keys()
将为您提供
phoneBook
字典中的键列表,即
Tom、Roberto和Sue
phoneBook[key]
给出相应的值

我想你的意思是把“518”和键的值连接起来?代码将键连接到值。您可以在代码中更改此行:

newKey = newStr + key
致:

当您打印
更新的ICT
时,这将为您提供所需:

{'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'}
产生:

{'Roberto': '518-564-0000', 'Sue': '518-564-0000', 'Tom': '518-564-0000'}

期望的输出是什么?
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'}