iterating one key in a python multidimensional associative array

安稳与你 提交于 2019-12-20 07:26:03

问题


I'm dynamically creating a 2 dimensional associative array (dictionary?)

I'm trying to loop through its keys - while keeping one of the indexes constant, so for instance all of the values associated to "key" with 'john' in its first bracket:

myhash['john']['smith'] = "address 1"
myhash['john']['doe'] = "address 2"

how can i get all of the keys of the hash for each "key" keeping the first index as 'john' (i want all of the last names)

Thanks


回答1:


myhash['john'] is itself a dictionary. (You aren't creating a multi-dimensional dictionary, but rather a dictionary of dictionaries.)

Thus...

last_names = list(myhash['john'])

or if you want to do something in a loop...

for last_name in myhash['john']:
    # do something with last_name



回答2:


I already mentionned it when answering your previous question : it looks like you're trying to reinvent the square wheel. Given your stated need, chances are you'll want to do a lookup on the lastname part too, and then it's either back to step 1 (browsing the whole dataset sequentially testing the "2nd-level" key) or maintaining a "lastname" index storing lastname:[firstname1, firstname2, firstnameN] which reduces (but not supress) the sequential browsing and needs to be updated on any insert or delete.

IOW you're reimplementing most of what a relational database can do, and it's very unlikely your implementation will be faster or more robust than even the cheaper RDB. For the record, there are very lightweight, file based (no need for a server process etc) RDB engines like SQLite3 (Python bindings are in the stdlib so you don't even have to install anything special).




回答3:


>>> for k in myhash['john']:
...     print(k)
... 
smith
doe


来源:https://stackoverflow.com/questions/11377908/iterating-one-key-in-a-python-multidimensional-associative-array

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