我有一本这样的字典:
>>> pprint.pprint(d) {'a': ('abc', 'pqr', 'xyz'), 'b': ('abc', 'lmn', 'uvw'), 'c': ('efg', 'xxx', 'yyy')}
Now, given a variable x
, I want to be able to list all the keys from the dict where the first element in the tuple is equal to x
. Hence I do this (on Python 2.6):
>>> [ k for k, v in d if v[0] == x ]
我得到
追溯(最近一次通话):
文件“”,第1行,位于
ValueError:需要多个值才能解压
我该如何纠正?
python大神给出的解决方案
您快到了,只是用dict忘记了.items()
:
>>> d = {'a': ('abc', 'pqr', 'xyz'),
... 'b': ('abc', 'lmn', 'uvw'),
... 'c': ('efg', 'xxx', 'yyy')}
>>> x = 'abc'
>>> [ k for k, v in d.items() if v[0] == x ]
['a', 'b']
如果您不想使用.items
,也可以对键本身进行迭代:
>>> [ k for k in d if d[k][0] == x ]
['a', 'b']