首页 > 解决方案 > python程序如何改变自己的代码

问题描述

在 python-3 中添加新对象后,联系人字典如何更改?我不想更改整个字典,我想向其中添加一个新对象,并且该对象也将添加到主代码中。

contacts = {'arman' : '123-355-1433',
            'samad' : '436-218-9818',}

print('hi welcom to my contacts.\nyou wanna check an existence contact or 
creat a new contact?')
creat_or_check = str(input())

if creat_or_check == 'check' :

    print('great, now who you wanna check?')
    contact_name = str(input())
    print(contacts[contact_name])

else :

    print('ok, now please first enter the name of the person then his number')
    enter_name = str(input('name : '))
    enter_number = str(input('number : '))
    contacts.update({enter_name : enter_number})
    print('the contact saved succesfully')

前任

从:

contacts = {'arman' : '123-355-1433',
            'samad' : '436-218-9818',}

至:

contacts = {'arman' : '123-355-1433',
            'samad' : '436-218-9818',
            'person' : 'number' }

标签: pythonpython-3.x

解决方案


与其更改代码,不如将“联系人”保存在单独的文件中,如 json 文件?例如:

import json
from pathlib import Path

# check if file already exists, if not start with empty dict
if Path("contacts.json").is_file():
    contacts = json.load(open("contacts.json", "r"))
else:
    contacts={}

print('hi welcom to my contacts.\nyou wanna check an existence contact or creat a new contact?')
creat_or_check = str(input())

if creat_or_check == 'check':

    print('great, now who you wanna check?')
    contact_name = str(input())
    print(contacts[contact_name])

else:

    print('ok, now please first enter the name of the person then his number')
    enter_name = str(input('name : '))
    enter_number = str(input('number : '))
    contacts[enter_name] = enter_number
    json.dump(contacts, open("contacts.json", "w"))
    print('the contact saved succesfully')

json文件:

{
  "arman": "123-355-1433",
  "samad": "436-218-9818"
}

推荐阅读