iterating one key in a python multidimensional associative array

前端 未结 3 506
礼貌的吻别
礼貌的吻别 2021-01-27 17:41

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 instan

相关标签:
3条回答
  • 2021-01-27 17:51

    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
    
    0 讨论(0)
  • 2021-01-27 18:02
    >>> for k in myhash['john']:
    ...     print(k)
    ... 
    smith
    doe
    
    0 讨论(0)
  • 2021-01-27 18:04

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

    0 讨论(0)
提交回复
热议问题