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

2024-10-03 13:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: keydefprintcopyrobertotomphonebooksue
3条回答

我认为你被字典的键和值弄糊涂了。执行phoneBook.keys()将为您提供phoneBook字典中的键列表,即Tom, Roberto and SuephoneBook[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'}

这就是你要找的吗?你知道吗

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()}

随机评论:

  • 你的phoneListdict,不要叫它list。你知道吗
  • 另外,对于变量:phone_list,方法:new_dict_with_area_codes,等等,遵循python命名约定

相关问题 更多 >