如何将现有键和值存储在初始化的空字典中



我是Python的新手,我已经编码以字典格式存储员工详细信息。我有澄清,首先我在代码的开头初始化了空字典 (user_details = {}(,然后执行它,我已经将所有值给了输入,

假设如果我重新运行代码意味着我需要从头开始再次输入所有详细信息,因为我在代码开头初始化了一个空字典。它会重置并清空所有现有详细信息。

如果我重新运行代码意味着,我需要从头开始输入值。如果我也重新运行代码,还有其他方法可以将现有详细信息存储在字典中。

如果我错了,请纠正我。

提前感谢您的时间!

user_details = {}
while True:
user_input = input(" You're Operation Please ( New / View ) Details : ").lower()
if user_input == 'new':
create_user_ID = input(" Enter the user ID :  ")
user_details[create_user_ID] = {}
user_name = input(" Enter the user name : ")
user_details[create_user_ID]['Name'] = user_name
user_age = int(input(" Enter the Age : "))
user_details[create_user_ID]['Age'] = user_age
user_occupation = input(" Enter the users occupation : ")
user_details[create_user_ID]['Occupation'] = user_occupation
user_department = input(" Enter the user department : ")
user_details[create_user_ID]['Department'] = user_department
user_income = int(input(" Enter the salary details : "))
user_details[create_user_ID]['Salary'] = user_income
user_address = input(" Enter the Address details ")
user_details[create_user_ID]['Address'] = user_address
print(f" New User account {create_user_ID} has been successfully created")
process = input(" Do you want to continue the Account creation process (YES / NO ) : ").lower()
if process == 'no':
break
elif user_input == 'view':
user_ID = input("Enter the user_ID : ")
print(user_details[user_ID])
break
else:
print(" Please enter the proper command to execute (new / view)")
for detail in user_details.items():
print(detail)

这应该开始:

d = {"1": 42, "None": "comfort"}
import csv
with open("f.txt", "w") as f:
writer = csv.writer(f)
writer.writerow(["key","value"])
# write every key/value pair as one csv-row
for key,value in d.items():
writer.writerow([key,value])
print(open("f.txt").read())
new_d = {}
with open("f.txt") as f:
reader = csv.reader(f)
next(reader) # skip header
# read every key/value pair from one csv-row, ignore empty lines
for line in reader:
if line:
key,value = line
new_d[key] = value
print(new_d)

输出:

# as file
key,value
1,42
None,comfort
# reloaded - all strings of course
{'1': '42', 'None': 'comfort'}

还要从 csv 模块中查找dict_writer/dict_reader。

使用泡菜,

In [11]: dict_to_store = dict(enumerate(['a']*10, 0))
In [12]: dict_to_store
Out[12]: 
{0: 'a',
1: 'a',
2: 'a',
3: 'a',
4: 'a',
5: 'a',
6: 'a',
7: 'a',
8: 'a',
9: 'a'}

与其他模块相比,泡菜要容易得多。例

将数据转储到文件

import pickle
pickle.dump(dict_to_store, open('file_out.txt', 'w'))

从转储的文件读取

In [13]: loaded_dict = pickle.load(open('file_out.txt', 'r'))
In [14]: loaded_dict
Out[14]: 
{0: 'a',
1: 'a',
2: 'a',
3: 'a',
4: 'a',
5: 'a',
6: 'a',
7: 'a',
8: 'a',
9: 'a'}

最新更新