Accessing Python dict values with the key start characters

后端 未结 7 1537
南笙
南笙 2020-12-28 13:56

I was wondering: would it be possible to access dict values with uncomplete keys (as long as there are not more than one entry for a given string)? For example:



        
7条回答
  •  天涯浪人
    2020-12-28 14:10

    You are not suggesting a coherent API:

    1. What should be the result of my_dict['']? You don't have a one-to-one mapping.
    2. How is it supposed to be extended to types other than str?

    Another reason you can't have it directly, even for strings and assuming you always return a list, is because Python's dict is implemented using a hash table, and it will map xy and xz to unrelated cells in the table.

    So, going the other way: such a lookup to would mean going for a slower implementation of dict, (which doesn't make sense, optimizing for an uncommon use) or being as slower as a full scan - which you may as well write it by hand, as it is not that common to be worth a dedicated convenience method.

提交回复
热议问题