2016-08-17 53 views
0

想象一下,我有一個名爲包含以下字典的文本「test_dict.txt」文件:的Python:如何修改值嵌套字典和擁有整個字典返回

{ 
    "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'}} 

但實際上我的第二個‘打印’給出了與第一個結果完全相同的結果。我猜這個問題要麼發生在深層拷貝中,要麼發生在函數返回的方式中,或者兩者兼而有之。我真的希望整個字典在轉換後返回,而不是一次產生一個項目。請有人幫忙糾正我的代碼嗎?

+0

'dc [k] = to_unicode(v)'? – jonrsharpe

+0

@jonrsharpe我在這行中使用的'unicode'是內置函數,將v轉換爲unicode類型,然後將其分配回相應的鍵。 –

+1

是的,但你不會在每次遞歸調用時分配回「主副本」,而是創建子樹的新副本並更新其中的一部分。因此我的建議如上。投入一些「印刷品」,看看發生了什麼。 – jonrsharpe

回答

0

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