第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

用新值替換 Python 字典值

用新值替換 Python 字典值

郎朗坤 2022-11-01 14:33:10
我正在使用文件的值來創(chuàng)建填充字典。我使用函數(shù)創(chuàng)建了文件: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'}))原始文件內(nèi)容:(abc)@(3)(def)@(ghj)3 是整數(shù)。我想維護(hù)字典中的數(shù)據(jù)類型,但目前字典返回 '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貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個贊

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


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


為此,您可以使用 python 字符串方法 .isdigit() 并在它返回 true 時轉(zhuǎn)換為 int ,或者如果您認(rèn)為大多數(shù)值將是整數(shù),您也可以嘗試使用 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:(如果您知道大多數(shù)將是整數(shù),則速度會更快,但如果相反,則速度會更慢)


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}


查看完整回答
反對 回復(fù) 2022-11-01
?
當(dāng)年話下

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超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)


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

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個贊

您正在測試解碼時的數(shù)字,但您可以嘗試將其設(shè)為 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)


查看完整回答
反對 回復(fù) 2022-11-01
  • 3 回答
  • 0 關(guān)注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號