python程序如何改变自己的代码

2024-05-28 18:43:03 发布

您现在位置: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')

e.x

发件人:

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

收件人:

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

Tags: orthe对象namenumberinputcheckcontact
2条回答

与其更改代码,不如将“联系人”保存在单独的文件中,比如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"
}

你可以像这样在字典里添加新的东西:

# original dictionary
contacts = {
 "arman": "123-355-1433",
  "samad": "436-218-9818"
}
contacts['NameHere'] = 0

对于json,缺少了一些东西。代码应该是这样的:

import json
filename = 'contacts.json'
try:
    with open(filename) as f_obj:
        contacts = json.load(f_obj)
except FileNotFoundError:
    contacts = {
 "arman": "123-355-1433",
  "samad": "436-218-9818"
}
with open(filename, 'w') as f_obj:
    json.dump(contacts, f_obj)

else:    
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')

相关问题 更多 >

    热门问题