如何避免在嵌套字典中添加重复值?

我有一个复杂的嵌套字典 - 但我已将我的问题简化为这个玩具示例。添加一个值会跨多个字典这样做,这不是故意的:


from collections import defaultdict

import json


Dist_T = defaultdict(lambda:([]))

Filter_T = defaultdict(lambda:Dist_T)

Phase_T = defaultdict(lambda:Filter_T)

    

Phase_T[60]['Green'][4].append('here')

Phase_T[60]['Green'][4].append('there')


Phase_T[60]['Blue'][4].append('over_there') #"over-there" will also be appended to the

                                            # list for the dictionary of the

                                            # Green key which is not intended


print (json.dumps(Phase_T, indent=2))

输出是:

{ "60": { "Green": { "4": [ "here", "there", "over_there" ] }, "Blue": { "4": [ "here", "there", "over_there" ] } } }


想要的是:

{ "60": { "Green": { "4": [ "here", "there"] }, "Blue": { "4": [ "over_there" ] } } }


慕容708150
浏览 101回答 1
1回答

汪汪一只猫

Phase_T你应该在一行中声明:Phase_T = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))Phase_T[60]['Green'][4].append('here')Phase_T[60]['Green'][4].append('there')Phase_T[60]['Blue'][4].append('over_there')print (json.dumps(Phase_T, indent=2))这打印:{  "60": {    "Green": {      "4": [        "here",        "there"      ]    },    "Blue": {      "4": [        "over_there"      ]    }  }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python