简体   繁体   English

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

[英]how to store the existing keys and values in the initialized empty dictionary

I'm newbie to Python, I have coded to store the employee details in the dictionary format. 我是Python的新手,我已经编码为以字典格式存储员工详细信息。 I have clarification like, first of all I've initialized empty dictionary (user_details = {}) in the start of my code and then executed it and I have given all the values to the inputs, 我得到的澄清是,首先,我在代码的开头初始化了空字典(user_details = {}),然后执行它,并将所有值赋予输入,

Suppose If I re-run the code means I need to enter all the details again from start, because I've initialized a empty dictionary in the starting of my code. 假设如果我重新运行代码,则意味着我需要从头开始再次输入所有详细信息,因为我已经在代码的开头初始化了一个空字典。 It resets and emptied all the existing details. 它将重置并清空所有现有细节。

If I re-run the code means, I need to enter the values from the start. 如果我重新运行代码,则需要从头开始输入值。 Is there any other way to store the existing details in the dictionary if I re-run the code also. 如果我也重新运行代码,是否还有其他方法可以将现有详细信息存储在字典中。

Please correct me, If I'm wrong. 请纠正我,如果我错了。

Thanks for your time in advance !! 谢谢您的时间提前!

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)

This should you get started: 您应该开始:

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)

Outputs: 输出:

# as file
key,value
1,42
None,comfort

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

Also lookup the dict_writer / dict_reader from the csv module . 还要从csv模块中查找dict_writer / dict_reader。

Using pickle, 用泡菜

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'}

pickle is lot more easier when compared to other modules. 与其他模块相比,泡菜要容易得多。 Example, 例,

Dumping data to file 将数据转储到文件

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

Reading from the dumped file 从转储文件中读取

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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM