2017-08-16 37 views
0

我嘗試合併兩個詞典以適合稍後進行發佈時出現問題。出於某種原因,get似乎是嵌套的,我不知道如何清理它。如果能夠獲得優化代碼的一些技巧,現在看起來有點麻煩。刪除嵌套鍵並將值移至主詞典鍵

for network in networks: 

      post_dict = {e1:e2 for e1,e2 in network['extattrs'].iteritems() if e1 not in keys } 
      pprint (post_dict['Stuff-Name']['value']) 

      post_dict['name'] = post_dict.pop('Stuff-Name') 
      post_dict['sid'] = post_dict.pop('Stuff-id') 

      dict_to_post = merge_two_dicts(post_dict, default_keys) 

網絡:

{u'_ref': u'ref number', 
u'comment': u'Name of object', 
u'extattrs': {u'Network-Type': {u'value': u'Internal'}, 
       u'Stuff-Id': {u'value': 110}, 
       u'Stuff-Name': {u'value': u'Name of object'}}, 
u'network': u'Subnet-A', 
u'network_view': u'default'} 

default_keys:

default_keys = {'status':'Active', 
       'group':None, 
       'site':'City-A', 
       'role':'Production', 
       'description':None, 
       'custom_fields':None, 
       'tenant':None} 

post_dict:

{'name': {u'value': u'Name of object'}, 
'sid': {u'value': 110}} 

所以,我想才達到是擺脫嵌套鍵(內鍵「名稱」和「SID」,所以鍵和值P空氣應該是「名稱:物體名稱」和「sid:110」

後置功能尚未定義。

+0

試着只發布重現問題所需的代碼。 '打破'在網絡中的蟒蛇循環網絡',只是給了我們'網絡','post_dict'和'default_keys'確切的字典 –

+0

清理了代碼 – Kirke

回答

0

在我的理解中,你的情況是非常具體的,我可能會去一個簡單的&骯髒的解決方案。首先你是否試過這個:

post_dict['name'] = (post_dict.pop('Stuff-Name'))['value'] 

其次,如何使用「過濾器和重命名」,並在那裏摺疊索引?這是不可取的,但如果你試圖做一個懶惰的解決方法,它就足夠了。我建議你跟我的第一個建議去,因爲我非常有信心它可以解決你的問題。

+0

看起來像這樣解決了它!是的,它是非常具體的,所以這工作正常,謝謝! – Kirke

0

要獲得任何嵌套字典的這第一個值,你可以使用這個

d = {'custom_fields': None, 'description': None, 'group': None, 'name': 
{'value': 'Name of object'}, 'role': 'Production', 'site': 'City-A', 
'status': 'Active', 'tenant': None, 'sid': {'value': 110}} 

for key in d.keys(): 
    if type(d[key]) == dict: 
    d[key] = d[key].popitem()[1] 

它返回

{'custom_fields': None, 'description': None, 'group': None, 'name': 'Name of 
object', 'role': 'Production', 'site': 'City-A', 'status': 'Active', 
'tenant': None, 'sid': 110} 

我認爲這是這一步是造成該詞典是嵌套在首位

post_dict['name'] = post_dict.pop('Stuff-Name') 
post_dict['sid'] = post_dict.pop('Stuff-id') 

你可以試試popitem()[1]這裏,如果你只會需要這樣的價值字典,而不是關鍵。

+0

似乎與你所定義的工作正常。在代碼中使用它產生另一種結果,但: { 'custom_fields':無, '說明':無, '羣':無, '名':{}, '角色': '生產', 'site':'City-A', 'status':'Active', 'tenant':None, 'sid':{}} – Kirke