iterating one key in a python multidimensional ass

2020-05-07 18:24发布

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

3条回答
smile是对你的礼貌
2楼-- · 2020-05-07 18:48

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
查看更多
家丑人穷心不美
3楼-- · 2020-05-07 18:49

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).

查看更多
爷的心禁止访问
4楼-- · 2020-05-07 19:08
>>> for k in myhash['john']:
...     print(k)
... 
smith
doe
查看更多
登录 后发表回答