Differences between revisions 1 and 2
Revision 1 as of 2004-02-25 20:08:51
Size: 1214
Editor: dsl254-010-130
Comment: Cute little technique I saw.
Revision 2 as of 2005-02-22 09:16:35
Size: 1198
Editor: aaron
Comment:
Deletions are marked like this. Additions are marked like this.
Line 14: Line 14:
def add_value_to_keys_list( dict_, key, value ):
    if dict_.has_key( key ):
        dict_[ key ] = [ value ] # construct list
def add_value_to_keys_list(dict_, key, value):
    if dict_.has_key(key):
        dict_[key] = [value] # Construct list
Line 18: Line 18:
        dict_[ key ].append( value ) # append to list         dict_[key].append(value) # Append to list
Line 25: Line 25:
def add_value_to_keys_list( dict_, key, value ):
    dict_.setdefault( key, [] ).append( value )
def add_value_to_keys_list(dict_, key, value):
    dict_.setdefault(key, []).append(value)

Keeping Lists in Dictionaries

Here's a cute technique I saw, for keeping lists inside dictionaries.

If you have a dictionary with list values, you can run into a problem when you need to add an item to a list value- does the list already exist?

Usually, we write it out like so:

   1 def add_value_to_keys_list(dict_, key, value):
   2     if dict_.has_key(key):
   3         dict_[key] = [value]  # Construct list
   4     else:
   5         dict_[key].append(value)  # Append to list

This is okay, but we can do even better!

   1 def add_value_to_keys_list(dict_, key, value):
   2     dict_.setdefault(key, []).append(value)

How does it work?

.setdefault works like .get, except that when the item isn't found, the default isn't only returned, but they key is set to the default as well.

So, in effect, the line means, "Look in the dictionary for the key. If it's there, return it's associate. If it's not there, set it's associate to [], and then return it's new associate. The associate is (surprise, surprise) - a list. Now, append the value to the list."

Cute!

KeepingListsInDictionaries (last edited 2009-10-22 19:58:15 by s235-138)

Unable to edit the page? See the FrontPage for instructions.