python字典键不起作用

时间:2014-01-23 23:13:50

标签: python defaultdict

我无法访问我制作的字典中的某些值。在我的代码中,我在阅读文件时制作了两个不同的词典。我的代码就是:

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'"])])

假设我有键值对{Aux:[“have”]}。 问题是,如果i = Aux,例如,x只是设置为空列表,当我实际上想要等于[“have”]时。

我不确定我正在做什么/访问不正确。有任何想法吗?谢谢!

2 个答案:

答案 0 :(得分:1)

我假设从阅读你的代码中你想要所有开始和结束的东西',对吗?在这种情况下,你可能想要

if RHS[0] == "'" and RHS[-1] == "'" :
    terminal_rules[LHS].append(RHS.strip())

因为0是字符串的第一个字符:)。如果'不是分割字符串的第二个字符,那么现在它将把所有内容添加到non_terminal_rules。

答案 1 :(得分:0)

如果您尝试将terminal_rules设置为nonterminal_rules中长度为1的每个键:值对,请执行以下操作:

nonterminal_rules = defaultdict(list)
terminal_rules = defaultdict(list)

for line in open(file, 'r').readlines():
# Do stuff here as you've done above

terminal_rules = {key:value for key,value in nonterminal_rules.items() if len(value) == 1}