可能重复:
iterating one key in a python multidimensional associative array
我在2维上创建了一本字典 myaddresses ['john','smith'] =“地址1” myaddresses ['john','doe'] =“地址2”
我如何以时尚的方式迭代一个维度
for key in myaddresses.keys('john'):
答案 0 :(得分:3)
坏消息:你不能(至少不是直接)。你所做的不是“2维”字典,而是带有元组的字典(在你的情况下是字符串对)作为键,并且只使用键的哈希值(通常使用哈希表)。你想要什么需要顺序查找,即:
for key, val in my_dict.items():
# no garantee we have string pair as key here
try:
firstname, lastname = key
except ValueError:
# not a pair...
continue
# this would require another try/except block since
# equality test on different types can raise anything
# but let's pretend it's ok :-/
if firstname == "john":
do_something_with(key, val)
毋庸置疑,这有点打败了使用词典的全部意义。呃......那么使用合适的关系数据库呢?
答案 1 :(得分:2)
尝试:
{k[1]:v for k,v in myaddresses.iteritems() if k[0]=='john'}
答案 2 :(得分:1)
它迭代所有键,所以它可能不是最有效的方法,但我只是陈述一个明显的方法,以防你忽略它:
for key in myaddresses.keys():
if key[0] == 'john':
print myaddresses[key]