python - 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' }
解决方案
与其更改代码,不如将“联系人”保存在单独的文件中,如 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"
}
推荐阅读
- php - 在我自己的 wordpress 主题中添加 the_post_thumbnail 作为 CSS 背景
- arrays - 如何为每个 CollectionView 部分设置不同的数据集?
- php - 添加谷歌职位发布时出现错误(索引 api)
- jquery - 当全选单击时,Jqgrid 数据未保存在已编辑的行上
- html - 来自 JSON 的 Angular 8 动态表单
- ios - 如何自动启动iOS App并禁止快速手动停止它
- couchdb - 如何在远程数据库中清除文档后重新复制文档
- c# - 在 C# 的派生类中覆盖枚举
- c# - 如何在 ASMX Web 服务上从客户端接收 XML?
- ios - iOS 和 Firebase 应用分发不想使用开发配置文件签署应用并分发它