[docs] addon/missing to section on dictionary in python 3.2.3

Bjorn Madsen bjorn.madsen at operationsresearchgroup.com
Wed Jul 25 11:22:57 CEST 2012


Hi,
Is it possible to add a very brief section/sentence in the documentation on
dictionaries
http://docs.python.org/py3k/tutorial/datastructures.html#dictionaries
that an efficient way of for example managing graphs is *to use joint
key-value pairs*?

I looked into the usage of graphs and found the common habit is to create
graphs as:
    G = {'s':{'u':10, 'x':5}, 'u':{'v':1, 'x':2}, 'v':{'y':4}, 'x':{'u':3,
'v':9, 'y':2}, 'y':{'s':7, 'v':6}}
   source:
http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/

However by using joint keys *d[key1,key2,...,keyN] = value* one may
actually set up pretty sophisticated data structures, which is brilliant
whenever m:n-relationships may occur.

I have put an example below:

def graph(vertices, connectivity):
    """This function produces a graph using joint keypairs in the returned
dictionary.
        Vertices must be integer.
        Connectivity is a floating point value between 0 and 1.
        A random number is produced.
        If the random number is less than or equal
        to the connectivity, then a node is added to the graph."""
    from random import random, randint
    d={}
    for i in range(1,vertices+1):
        for j in range(1,vertices+1):
            if random()<=connectivity:
                d[i,j]=randint(1,10)    # dict uses joint key-pair!
    return d

Further discussion could of course be how to lookup keys "if the graph is
bidirectional?" This however may easily be solved using multiple
assignments such as:
if keyA>keyB:
    keyA, keyB = keyB, keyA
...where these two lines reduces the otherwise redundant part of the
dictionary to half the size.

Finally I assume that the performance of using joint keys is the same (or
perhaps slightly faster) than using Eppstein's method (top example), as it
is not necessary to parse the result value from the first dictionary into
the second. However please correct me if I'm wrong on this matter.


PS. If this subject has been evaluated before, please accept my apologies;
I only started with python 3 three weeks ago and haven't gotten my head
around the PEP yet, but thought it could be advantageous to know this since
it was absent in the documentation.

Kind Regards,
-- 
Bjorn Madsen
*Researcher Complex Systems Research*
Ph.: (+44) 0 7792 030 720
bjorn.madsen at operationsresearchgroup.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/docs/attachments/20120725/ba63053f/attachment.html>


More information about the docs mailing list