[Tutor] dictionaries help
Alan Gauld
alan.gauld at btinternet.com
Thu Jul 23 19:01:39 CEST 2009
<davidwilson at Safe-mail.net> wrote
> i would like to understand how dictionaries work.
They work like a lookup table.
You provide a key and lookup the corresponding value
in the dictionary. So to implement a traditional language
dictionary the keys would be words and the values would
be a list of definitions.
You read them by placing the key in square brackets,
or by using the get() method:
> for example:
>>>> my_lst = [{'code': 'aaa', 'name': 'a name'}, {'code': 'bbb', 'name':
>>>> 'b name'}]
my_lst[0]['code'] -> 'aaa'
my_lst[0].get('code', 0) -> 'aaa' or 0 if 'aaa' does not exist as a key
You can write to them using the [] notation too:
my_lst[0]['name'] = 'A new name' changes the value for name in the
first dictionary.
>>>> my_code = 'aaa'
> from the above i would like to compare my_code and return the
> dictionary which has code == my_code
Vince has shown you one way, this is another way:
def findDict(value, dictList):
for dct in dictList:
if dct.get('code', '') == my_code
return dct
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list