亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用新值替換 Python 字典值

用新值替換 Python 字典值

郎朗坤 2022-11-01 14:33:10
我正在使用文件的值來創建填充字典。我使用函數創建了文件:def save_dict_to_file(filename, dictionary):  # done    with open(filename, 'w') as w:        for key in dictionary:            w.write("(")            w.write(key)            w.write(")")            w.write("@(")            w.write(str(dictionary[key]))            w.write(")")            w.write("\n")print (save_dict_to_file('save_dict_to_file_example.txt', {'abc':3,'def':'ghj'}))原始文件內容:(abc)@(3)(def)@(ghj)3 是整數。我想維護字典中的數據類型,但目前字典返回 '3' 作為字符串:{'abc': '3', 'def': 'ghj'}這是我的完整代碼:def load_dict_from_file(filename):    with open(filename, 'r') as r:        dictionary = dict()        file_contents=r.readlines()        for line in file_contents:            #line=line.strip()            index=line.index('@')            key=line[1:index-1] #before the @            value=line[index+2:-2] #after the @            value=value.strip()            dictionary[key]=value            for character in key,value:                if character.isdigit():                    index_character=character.index                    new_character = int(character)                else:                    continue    print(dictionary)如何從字典中刪除舊字符并將其替換為新字符?
查看完整描述

3 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

我將回答我認為您要問的問題。如果我誤解了,請糾正我!


我相信您在問如何將 txt 文件中的數字讀取為整數。不幸的是,我不完全知道這個文件的目的或結構是什么,但我猜想它是將@符號左側括號內的文本映射到括號內的文本到@ 符號的右側。根據您的代碼文件示例,這將是{'abc': 3, 'def': 'ghj'}.


為此,您可以使用 python 字符串方法 .isdigit() 并在它返回 true 時轉換為 int ,或者如果您認為大多數值將是整數,您也可以嘗試使用 ValueError 除外它。這是兩種方法:


# PSEUDOCODE

file_dictionary = {}

for each line in file:

    key = ...

    value = ...

    # HERE GOES SOLUTION 1 OR 2

解決方案 1:


if value.isdigit():

    file_dictionary[key] = int(value)

else:

    file_dictionary[key] = value

解決方案2:(如果您知道大多數將是整數,則速度會更快,但如果相反,則速度會更慢)


try:

    file_dictionary[key] = int(value)

except ValueError:

    file_dictionary[key] = value

如果要編輯字典值,只需訪問要編輯的值并將其分配給另一個值。例如:file_dictionary['abc'] = 3 如果你想編輯一個鍵,你必須分配新鍵的值并刪除舊鍵。前任:


file_dictionary = {'abd' = 3}  # Create the dictionary

file_dictionary['abc'] = 3  # file_dictionary now = {'abc': 3, 'abd': 3}

file_dictionary.pop('abd')  # file_dictionary now = {'abc': 3}


查看完整回答
反對 回復 2022-11-01
?
當年話下

TA貢獻1890條經驗 獲得超9個贊

希望在這個奇怪的時期一切順利。


首先,您可以使用格式化來簡化您的代碼編寫。


def save_dict_to_file(filename, dictionary):  # done

    with open(filename, 'w') as w:

    for key in dictionary:

        w.write("({})@({})\n".format(key, dictionary[key]))

但是有更簡單的方法可以將字典保存在文件中。例如,您可以簡單地將其寫入文件或腌制它。


對于加載部分:


def load_dict_from_file(filename):

    with open(filename, 'r') as r:

        dictionary = {}

        file_contents = r.readlines()

        for line in file_contents:

            key, value = line.split('@')

            if key.isdigit():

                key = int(key.strip())

            if value.isdigit():

                value = int(value.strip())   

        dictionary[key]=value


    print(dictionary)


查看完整回答
反對 回復 2022-11-01
?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

您正在測試解碼時的數字,但您可以嘗試將其設為 anint并在失敗時捕獲異常。


def load_dict_from_file(filename):

    with open(filename, 'r') as r:

        dictionary = dict()

        file_contents=r.readlines()

        for line in file_contents:

            #line=line.strip()

            index=line.index('@')

            key=line[1:index-1] #before the @

            value=line[index+2:-2] #after the @

            value=value.strip()

            # see if its an int

            try:

                value = int(value)

            execpt ValueError:

                pass

            dictionary[key]=value

    print(dictionary)


查看完整回答
反對 回復 2022-11-01
  • 3 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號