Search in list of dictionaries

MRAB google at mrabarnett.plus.com
Thu Feb 19 18:39:04 CET 2009


Alex Gusarov wrote:
> Hello everybody!
> 
> I've a list of dictionaries with 'shorcut' and 'command' keys. When user 
> types a word program must search this list for a typed shortcut and then 
> run linked command. What I've wrote:
> 
>         for cmd in self.commands:
>             if cmd['shortcut'] == input:
>                 os.popen(cmd['command'])
>                 break
>         else:
>             os.popen(input)
> 
> But it's a brute-force method and I think there is another way in 
> searching items through a list by dictionary key. Please give me advice 
> how can I implement fast search in list of dictionaries by some 
> dictionary key. In my mind language:
> 
> list.get({'shortcut' == input})
> 
If want to go from the shortcut to the command (cmd['shortcut'] ->
cmd['command']) the quickest way is using a dict, where cmd['shortcut']
is the key and cmd['command'] is the value:

     self.command_dict = {}
     for cmd in self.commands:
         self.command_dict[cmd['shortcut']] = cmd['command']

and then:

     os.popen(self.command_dict[input])

This will raise a KeyError if it's unknown. The equivalent of your code
above is:

     os.popen(self.command_dict.get(input, input))



More information about the Python-list mailing list