<分区>
Possible Duplicate:
iterating one key in a python multidimensional associative array
我创建了一个二维字典 myaddresses['john','smith'] = "地址 1" myaddresses['john','doe'] = "地址 2"
我如何迭代时尚中的一个维度
for key in myaddresses.keys('john'):
<分区>
Possible Duplicate:
iterating one key in a python multidimensional associative array
我创建了一个二维字典 myaddresses['john','smith'] = "地址 1" myaddresses['john','doe'] = "地址 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)
不用说,它有点破坏了使用字典的全部意义。错误...改用适当的关系数据库怎么样?
关于python - 迭代 python 字典中的单个维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378048/