Accessing Python dict values with the key start characters

后端 未结 7 1560
南笙
南笙 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:03

    Sure it is possible:

    print next(val for key, val in my_dict.iteritems() if key.startswith('Date'))
    

    but this incurs a full scan through the dictionary. It only finds the first such matching key (where 'first' is arbitrary) and raises StopIteration instead of KeyError if no keys match.

    To get closer to what you are thinking of, it's better to write this as a function:

    def value_by_key_prefix(d, partial):
        matches = [val for key, val in d.iteritems() if key.startswith(partial)]
        if not matches:
            raise KeyError(partial)
        if len(matches) > 1:
            raise ValueError('{} matches more than one key'.format(partial))
        return matches[0]
    

提交回复
热议问题