[Python-ideas] matrix operations on dict :)

Terry Reedy tjreedy at udel.edu
Tue Feb 7 04:20:14 CET 2012

On 2/6/2012 8:00 PM, julien tayon wrote:

> Lets define the notion of dict(dict()) (rooted k-ary trees) as a
> vector. Imagine :
> tree A
> { a:
>      { b : 1,
>        c : 2
>      },
>    e : 3.0
> }
> This is the same as
> vector B
> dict(
>   tuple([ 'a', 'b' ]) = 1,
>   tuple([ 'a', 'c' ]) = 2,
>   tuple([ e ]) = 3.0
> )

Adding quotes makes it different from tree A. The difference is 
important because a dict simulates a (sparse) array only if the keys are 
ordered (or are ordered sequences of ordered objects). Strings are 
ordered, but not general objects.

There is no need to write tuples as tuple(somelist)
   ('a', 'b') = 1
   ('a', 'c') = 2
   ('e',) = 3.0

Since your definitions of + and * on dicts does not use order, using the 
terms 'vector' and 'matrix' just seem distracting to me. The only thing 
you are extracting from them is the idea of component-wise operations on 
collections. What is important is whether the operations apply to the 

Whenever one has a dict whose values are lists, it is common to start 
with empty lists and add items to the list for each key with
You could imagine this operation as performing your dict addition
    d + {key:[val]}
in place and then performing standard list addition in place (.extend).
But thinking this way has limited use.

In actual application, the code is likely to be something like:
   for key,val in source:

There are three points here.
1. These patterns are specific to subcategories of dicts.
2. For dicts (and sets and lists), in-place modification is more common 
than creating new dicts (or sets or lists). Python is not mathematics, 
and it is not a functional, side-effect-free language.
3. The source of modifiers is usually an iterator -- a category rather 
than a class. The iterator does not have to be based on a dict and 
typically is not.

The same points apply to lists. list1 + list2 is rare compared to 
list1.append(item) and list1.extend(iterable_of_items). And of course, 
both apply to all lists and objects and iterables, rather than 
specialized subcategories.

Terry Jan Reedy

More information about the Python-ideas mailing list