Python:如何修改嵌套字典中的值并返回整个dict

2024-10-03 11:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个名为“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\u 1”、“str\u 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)

我在函数“tounicode”中使用了递归,以便遍历到最深的值。第一个'print'给出'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',因此函数返回的dictionary对象应该如下打印:

{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中,要么发生在函数的返回方式中,甚至两者都有。我真的希望整本词典在转换后都能被退回,而不是一次只返回一个条目。有人能帮我修改密码吗?你知道吗


Tags: 文件函数jsonstringunicodeintegerdcdict
1条回答
网友
1楼 · 发布于 2024-10-03 11:25:58

正如@jornsharpe所提到的,您只需要将内容分配回主副本或原始副本。下面是一些意大利面条,重复您提供的代码:

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

相关问题 更多 >