iterate over a single dimension in python dictionary [duplicate]

删除回忆录丶 提交于 2019-12-14 02:25:37

问题


Possible Duplicate:
iterating one key in a python multidimensional associative array

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'):

回答1:


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 ?




回答2:


Try:

{k[1]:v for k,v in myaddresses.iteritems() if k[0]=='john'}



回答3:


It iterates over all keys, so it might not be the most efficient way, but I'll just state the obvious method in case you overlooked it:

for key in myaddresses.keys():
    if key[0] == 'john':
        print myaddresses[key]


来源:https://stackoverflow.com/questions/11378048/iterate-over-a-single-dimension-in-python-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!