我無法訪問我製作的字典中的某些值。在我的代碼中,我在閱讀文件時做了兩個不同的字典。我的代碼是這樣的:python字典鍵不工作
nonterminal_rules = defaultdict(list)
terminal_rules = defaultdict(list)
for line in open(file, 'r').readlines():
LHS,RHS = line.strip().split("->")
if RHS[1] == "'" and RHS[-1] == "'" :
terminal_rules[LHS].append(RHS.strip())
else:
nonterminal_rules[LHS].append(RHS.split())
for i in nonterminal_rules:
for j in nonterminal_rules[i]:
if len(j) == 1:
x = terminal_rules[j[0]])
這裏是鍵值,以我的字典:
print(self.original_grammar.terminal_rules.items())
dict_items([('NN ', ["'body'", "'case'", "'immunity'", "'malaria'", "'mouse'", "'pathogen'", "'research'", "'researcher'", "'response'", "'sepsis'", "'system'", "'type'", "'vaccine'"]), ('NNS ', ["'cells'", "'fragments'", "'humans'", "'infections'", "'mice'", "'Scientists'"]), ('Prep ', ["'In'", "'with'", "'in'", "'of'", "'by'"]), ('IN ', ["'that'"]), ('Adv ', ["'today'", "'online'"]), ('PRP ', ["'this'", "'them'", "'They'"]), ('Det ', ["'a'", "'A'", "'the'", "'The'"]), ('RP ', ["'down'"]), ('AuxZ ', ["'is'", "'was'"]), ('VBN ', ["'alerted'", "'compromised'", "'made'"]), ('Adj ', ["'dendritic'", "'immune'", "'infected'", "'new'", "'Systemic'", "'weak'", "'whole'", "'live'"]), ('VBN ', ["'discovered'"]), ('Aux ', ["'have'"]), ('VBD ', ["'alerted'", "'injected'", "'published'", "'rescued'", "'restored'", "'was'"]), ('COM ', ["','"]), ('PUNC ', ["'?'", "'.'"]), ('PossPro ', ["'their'", "'Their'"]), ('MD ', ["'Will'"]), ('Conj ', ["'and'"]), ('VBP ', ["'alert'", "'capture'", "'display'", "'have'", "'overstimulate'"]), ('VB ', ["'work'"]), ('VBZ ', ["'invades'", "'is'", "'shuts'"]), ('NNP ', ["'Dr'", "'Jose'", "'Villadangos'"])])
比方說,我有鍵值對{奧克斯:「有」]}。 問題是,如果我=輔助,例如,x只是設置爲一個空列表,當我真的想等於[「有」]。
我不知道我在做什麼/訪問不正確。有任何想法嗎?謝謝!
這將會是可能更容易顯示輸出的結果self.original_grammar.terminal_rules.items(),並且您可能想要爲terminal_rules和non_terminal_rules顯示它。以這種方式查看字典會更容易,而不必單獨查看鍵/值。 – DivineWolfwood
您的輸出中沒有空列表,'['','「]'不被視爲空列表。 –
與鍵:值對'{「Aux」:[「have」]}','i ==「Aux」','nonterminal_rules [i] == [「have」]'和'terminal_rules [j [ 0]]'是'KeyError',這意味着對於'defaultdict(list)'它創建一個空列表並將其分配給'x'。 –