可能重复:
在 python 多维关联数组中迭代一个键
我创建了一个二维字典 myaddresses['john','smith'] = "address 1" myaddresses['john','doe'] = "address 2"
我如何以时尚方式迭代一维
for key in myaddresses.keys('john'):
可能重复:
在 python 多维关联数组中迭代一个键
我创建了一个二维字典 myaddresses['john','smith'] = "address 1" myaddresses['john','doe'] = "address 2"
我如何以时尚方式迭代一维
for key in myaddresses.keys('john'):
坏消息:你不能(至少不能直接)。您所做的不是“二维”字典,而是以元组(在您的情况下为字符串对)作为键的字典,并且仅使用键的哈希值(通常使用哈希表)。您想要的需要顺序查找,即:
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)
不用说,它有点打败了使用 dict 的全部意义。错误...如何使用适当的关系数据库来代替?
尝试:
{k[1]:v for k,v in myaddresses.iteritems() if k[0]=='john'}
它遍历所有键,因此它可能不是最有效的方法,但我将仅说明显而易见的方法,以防您忽略它:
for key in myaddresses.keys():
if key[0] == 'john':
print myaddresses[key]