簡體   English   中英

如何在已初始化的空字典中存儲現有鍵和值

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM