Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Python dict values with the key start characters

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:

my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'} print my_dict['Date'] >> '15th july' 

Is this possible? How could it be done?

like image 250
Roman Rdgz Avatar asked Jun 14 '13 10:06

Roman Rdgz


People also ask

Can we access the keys from values in dictionary Python?

We can also fetch the key from a value by matching all the values using the dict. item() and then print the corresponding key to the given value.

Are dictionary values accessed by keys?

A Python dictionary is a collection of key-value pairs, where each key has an associated value. Use square brackets or get() method to access a value by its key. Use the del statement to remove a key-value pair by the key from the dictionary.


2 Answers

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'] 
like image 148
Ashwini Chaudhary Avatar answered Oct 16 '22 10:10

Ashwini Chaudhary


not the best solution, can be improved (overide getitem)

class mydict(dict):     def __getitem__(self, value):         keys = [k for k in self.keys() if value in k]         key = keys[0] if keys else None         return self.get(key)   my_dict = mydict({'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'}) print(my_dict['Date'])# returns 15th july 
like image 26
Ali SAID OMAR Avatar answered Oct 16 '22 09:10

Ali SAID OMAR