【问题标题】:Python: How to modify values in nested dictionary and have the whole dict returnedPython:如何修改嵌套字典中的值并返回整个字典
【发布时间】:2016-08-17 20:13:01
【问题描述】:

假设我有一个名为“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”中使用了递归来遍历最深的值。第一个 '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',所以函数返回的字典对象应该是这样打印的:

{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 中,要么发生在函数返回的方式中,或者两者兼而有之。我真的希望在转换后返回整个字典,而不是一次产生一个项目。有人可以帮忙更正我的代码吗?

【问题讨论】:

  • dc[k] = to_unicode(v)?
  • @jonrsharpe 我在这一行中使用的 'unicode' 是内置函数,将 v 转换为 unicode 类型,然后将其分配回其对应的键。
  • 是的,但是您不会在每次递归调用时分配回“主副本”,而是创建子树的新副本并更新其中的一部分。因此我上面的建议。扔一些prints 看看发生了什么。

标签: python dictionary unicode


【解决方案1】:

正如@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

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2018-09-13
    • 2013-11-30
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2018-07-10
    • 2016-09-30
    相关资源
    最近更新 更多