У меня есть этот метод, который генерирует ориентированный граф в виде словаря, где значения ключа являются узлами, на которые указывает ключ, т. Е. {'Stack': [ «над», «поток»]}, стек точек снова и течь ...Python: использование наборов в сочетании со словарями
def generateGraph(fileName):
heroDict = {}
graph = {}
with open(fileName) as inFile:
for line in inFile:#go through each line
name_comic = line.rstrip().replace('"', '').split('\t') #split into list with name and comic book as strings
if name_comic[1] in heroDict: #if the comic book is already in the dictionary
heroDict[name_comic[1]] += [name_comic[0]] #add the hero into the comic's list of heroes
else:
heroDict.update({name_comic[1]: [name_comic[0]]}) # update dictionary with name and comic book
for i in heroDict.values():
for j in i:
if graph.has_key(j):
tempDict = copy.deepcopy(i)
tempDict.remove(j)
heroList = tempDict
graph[j] += heroList
else:
tempDict = copy.deepcopy(i)
tempDict.remove(j)
heroList = tempDict
graph[j] = heroList
print graph #<========== the graph has duplicates, ie, values that are the same as their keys are present
return graph
Мой вопрос, как я могу реализовать использование наборов с словарей, чтобы предотвратить значения, которые являются такими же, как ключ в вопросе, который нужно добавить к ключу?
Зачем нужна глубокая копия? –
И почему бы не просто проверить для 'if j not in heroList' здесь? –
deepcopying - это то, что я могу удалить ключ, не удаляя ключ из основного словаря im, используя – Ogen