Как избежать добавления повторяющихся значений во вложенные словари?

#python #dictionary #nested #duplicates

#python #словарь #вложенный #дубликаты

Вопрос:

У меня сложный вложенный словарь, но я упростил свою проблему до этого игрушечного примера. Добавление значения делает это в нескольких словарях, и это не предназначено:

 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" ] } } }

Ответ №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"
      ]
    }
  }
}
  

Комментарии:

1. Давай! Это тонко. Спасибо! Я не понимаю, почему это имеет значение — я потратил на это довольно много часов.