Searching Dictionary

MRAB python at mrabarnett.plus.com
Wed Sep 23 17:44:00 EDT 2009


Support Desk wrote:
> Sorry for the confusion, Simon, this is almost exactly what I need, but 
> i need to be able to search for a string in a given value of an item  
> 
> Here is an example of the dict I am working with
> 
> {'252': [{'code': '51679', 'date': '2009-08-01 11:35:38', 'userfield': 
> '252', 'from': '9876662881', 'to': '19877760406', 'fpld': '"Foobar" 
> <9855562881>', 'result': 'ANSW', 'sec': 131}, {'code': '51679', 'date': 
> '2009-08-01 14:33:55', 'userfield': '252', 'from': '9876662881', 'to': 
> '19877770391', 'fpld': '"Foobar" <9876555881>', 'result': 'ANSW', 'sec': 
> 86}]}
> 
> 
> 252 being the key, I need to be able to search for a string in a given 
> item , say 777 in the 'to' field so 
> 
> print wtf(dict,'to','777')
> 
> would return
> 
> {'252': [{'code': '51679', 'date': '2009-08-01 11:35:38', 'userfield': 
> '252', 'from': '9876662881', 'to': '19877760406', 'fpld': '"Brochsteins" 
> <9855562881>', 'result': 'ANSWERED', 'billsec': 131}, {'code': '51679', 
> 'date': '2009-08-01 14:33:55', 'userfield': '252', 'from': '9876662881', 
> 'to': '19877770391', 'fpld': '"Brochsteins" <9876555881>', 'result': 
> 'ANSWERED', 'billsec': 86}]}
> 
> I hope this makes sense, sorry for not being clear
> 
[snip]
Is this what you want?

def wtf(big_dict, search_key, search_value):
     result = {}
     for key, value in big_dict.iteritems():
         if search_value in value[0][search_key]:
             result[key] = value
     return result



More information about the Python-list mailing list