问题描述
我在2维上创建了一个字典 myaddresses ['john','smith'] =地址1" myaddresses ['john','doe'] =地址2"
i created a dictionary on 2 dimensions myaddresses['john','smith'] = "address 1" myaddresses['john','doe'] = "address 2"
我该如何以一种方式迭代一个维度
How can i iterate over one dimension in the fashion
for key in myaddresses.keys('john'):
推荐答案
坏消息:你不能(至少不是直接).您所做的不是"2维"字典,而是以元组(在您的情况下为字符串对)作为键的字典,并且仅使用键的哈希值(通常与哈希表一起使用).您想要的内容需要顺序查找,即:
Bad news: you can't (not directly at least). What you did was not a "2 dimensions" dict, but a dict with tuples (string pairs in your case) as keys, and only the hash value of the key is used (as usually with hashtables). What you want requires a sequential lookup, ie:
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)
毋庸置疑,这在使用字典的整个意义上都是失败的.错误...使用适当的关系数据库又如何呢?
Needless to say that it kind of defeat the whole point of using a dict. Err... what about using a proper relational DB instead ?
这篇关于迭代python字典中的一个维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!