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:
You can't do such directly with dict[keyword]
, you've to iterate through the dict and match each key against the keyword and return the corresponding value if the keyword is found.
This is going to be an O(N)
operation.
>>> my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'}
>>> next(v for k,v in my_dict.items() if 'Date' in k)
'15th july'
To get all such values use a list comprehension:
>>> [ v for k,v in my_dict.items() if 'Date' in k]
['15th july']
use str.startswith
if you want only those values whose keys starts with 'Date':
>>> next( v for k,v in my_dict.items() if k.startswith('Date'))
'15th july'
>>> [ v for k,v in my_dict.items() if k.startswith('Date')]
['15th july']