从python中的字典中获取价值

时间:2016-05-06 19:18:09

标签: python python-2.7 dictionary

我有以下字典:

index=  {(V, NP): VP, ('the',): Det, ('shot',): V, (V, NP, Det, Nom): VP, (Det, Nom): NP, ('Harry',): PropN, (N,): Nom, (P, VP): PP, ('dog',): N, (V,): VP, (V, S): VP, ('thinks',): V, ('Mary',): PropN, ('eager',): Adj, (NP, VP, Conj, Clause): Clause, ('gave',): V, (NP, VP): RelClause, ('give',): V, ('to',): P, (V, Adj, PP): VP, ('is',): V, ('cat',): N, (Clause,): S, ('easy',): Adj, (Adj, Nom): Nom, ('my',): Det, ('flower',): N, (V, NP, PP): VP, ('i',): PropN, (V, NP, Whw, RelClause): VP, (V, Adj): VP, ('policeman',): N, ('please',): V, ('a',): Det, ('pajamas',): N, ('This',): PropN, ('very',): Adj, ('John',): PropN, ('that',): Whw, ('said',): V, (PropN,): NP, ('pis',): V, ('chased',): V, ('apple',): N, (P, NP): PP, ('I',): PropN, ('elephant',): N, (VP, NP): RelClause, ('book',): N, ('an',): Det, ('heavy',): Adj, ('teacher',): N, ('persuaded',): V}

如果我试图通过以下方式获得价值:

index.get('(V,NP)')

它什么都不返回。我如何检索值?

ps:我已经尝试了几乎所有的组合来从字典中获取内容。

3 个答案:

答案 0 :(得分:0)

您需要index.get((V, NP)),而不是index.get('(V, NP)')

答案 1 :(得分:0)

您应该尝试index.get(('V', 'NP'))index.get((V, NP))(取决于元组'项目是字符串还是变量)而不是index.get('(V, NP)')

答案 2 :(得分:0)

看起来您的密钥是变量元组而不是字符串。您必须使用相同的密钥来检索值,例如

>>>index = {(1,2):3}

>>>index['(1,2)']# this will fail
KeyError: '(1,2)'

>>>index[(1,2)]
3