Search in list of dictionaries

Alex Gusarov amgusarov at gmail.com
Thu Feb 19 12:53:19 EST 2009


Thanks! This example is quite simple and works exactly the way I wanted.

On Thu, Feb 19, 2009 at 11:39 PM, MRAB <google at mrabarnett.plus.com> wrote:

> 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))
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090219/0464835a/attachment-0001.html>


More information about the Python-list mailing list