簡體   English   中英

Python:如何修改嵌套字典中的值並返回整個字典

[英]Python: How to modify values in nested dictionary and have the whole dict returned

想象一下,我有一個名為“ test_dict.txt”的文件,其中包含以下類似於字典的文本:

{
    "subdic1" : {
        "a_string" : "something1",
        "a_integer" : 16,
        "a_list" : [
            "str_1",
            "str_2"
        ]
    },
    "subdic2" : {
        "a_string" : "something2",
        "a_integer" : 32,
        "a_list" : [
            "str_3",
            "str_4"
        ]
    }
}

如您所見,有嵌套的字典。 我想要做的就是將所有最深的值(“ something1”,16 [[str_1”,“ str_2”]等)轉換為unicode類型的對象,以進行比較。 這是我的嘗試:

import json
from copy import deepcopy

def to_unicode(d):
    dc = deepcopy(d)
    for k,v in dc.iteritems():
        if isinstance(v, dict):
            to_unicode(v)
        else:
            dc[k] = unicode(v)
    return dc

dict_fname = 'test_dict.txt'
with open(dict_fname) as dict_fd:
    dic = json.load(dict_fd)
print dic
print to_unicode(dic)

為了遍歷最深的值,我在函數“ to_unicode”中使用了遞歸。 第一個“打印”給出“ json.load”操作的結果,如下所示:

{u'subdic1': {u'a_list': [u'str_1', u'str_2'], u'a_integer': 16, u'a_string': u'something1'}, u'subdic2': {u'a_list': [u'str_3', u'str_4'], u'a_integer': 32, u'a_string': u'something2'}}

因此,我真正應該轉換為unicode類型的是兩個整數16和32。但是為了簡化起見,我仍然希望該函數在字典的每個級別內轉換每個值。 應該將這兩個數字轉換為u'16'和u'32',因此該函數返回的字典對象應該像這樣打印:

{u'subdic1': {u'a_list': [u'str_1', u'str_2'], u'a_integer': u'16', u'a_string': u'something1'}, u'subdic2': {u'a_list': [u'str_3', u'str_4'], u'a_integer': u'32', u'a_string': u'something2'}}

但實際上,我的第二張“印刷品”給出的結果與第一張印刷品完全相同。 我猜問題可能是在Deepcopy中或在函數返回的方式中發生的,或者甚至同時發生。 我真的希望整個字典在轉換后返回,而不是一次產生一項。 有人可以幫忙更正我的代碼嗎?

正如@jonrsharpe提到的,您只需要將內容分配回原版或原始副本即可。 這是一些意大利細面條,可根據您提供的代碼進行迭代:

def to_unicode(d, target_dict={}):
    for k,v in d.iteritems(): 
        if isinstance(v, dict): 
            target_dict = to_unicode(v, target_dict)
        else: 
            target_dict[k] = unicode(v)
    return target_dict

暫無
暫無

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

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