Dict Help

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Jul 15 21:33:27 CEST 2007

En Sun, 15 Jul 2007 11:39:24 -0300, Robert Rawlins  
<robert_rawlins at hotmail.com> escribió:

> I'm looking for some help expanding on a dictionary I've got and storing  
> multiple values per key and the best way to do it. I'm guessing that I  
> need to store a list inside the value of the dictionary, but I'm not  
> quite sure how that can be achieved, and also how to check for values in  
> that list.
> Here is a brief example of what I want to be able to build:
> Key                                          Value
> 00:0F:DE:A8:AB:6F                      
> 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F.gif,533EAE0F-B211-B2D8-4C2DB662CCECFBD7.3gp
> 00:17:B0:A0:E7:09                      
> 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F.gif
> 00:1B:98:16:21:E4                      
> 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg

There are a few ways to do it. Just translating your own words into  
Python, use a dictionary with a list of values.

> Now I really need to have two functions, one of which appends a value to  
> the list for a specified key, so I have the key and the new value as  
> strings, I then want to locate that key and append the list with the new  
> value.

The simplest way:

d = {}
# add a pair key, value
if key not in d:
   d[key] = [value]

> The second function I need, is to check for the existence of a value in  
> the list of a particular key, again I have the key and the value and I  
> want to do something like:
> if value in list of values for key:
>        do something here...

# check for a key, value
exists = key in d and value in d[key]

> The final function that would be helpful to me would to be able to  
> remove a value from the list for a specific key.

# remove value from key's values
if key in d and value in d[key]:

> I'm not sure if a list as the value in a dict is possible, or if its the  
> best way to achieve this, It just made logic sense to me so thought I'd  
> come and get your thoughts on this. If anyone has any better suggestions

It's perfectly possible as you can see. Now, depending on how many values  
you have, or how often do you test, you might replace the list with a set.  
Sets are unordered collections (you will loose the insertion order) but  
are better suited for a "contains" test (O(1) instead of O(n) for a list)
And you might replace the dictionary with a defaultdict. The insertion  
would become:

 from collections import defaultdict
d = defaultdict(set)
# add a pair key, value

The existence check and remove method do not change.

Dicts, lists and sets are documented here:  
<http://docs.python.org/lib/types.html> and defaultdict  

Gabriel Genellina

More information about the Python-list mailing list