When one is not using methods, what is the best, way to achieve the following.
- have a single function for adding items to a dictionary
- use that function when adding multiple items to the dictionary
- Does this make everything super slow?
The following works, I am not very serious about using it, but am interested in what is possible.
Simple functions to create, and update a dictionary.
from collections import defaultdict
from functools import partial
def addfoo(mydict, foo):
x,y,z = foo
mydict[x].add((y,z))
mydict[y].add((x,z))
return mydict
makemydict = partial(addfoo, defaultdict(set))
foo = ('foo','bar',1)
mydict = makemydict(foo)
print(mydict)
# defaultdict(<class 'set'>, {'foo': {('bar', 1)}, 'bar': {('foo', 1)}})
While the next part of this works, I was wondering if there was a way to use map, to run the function over the ‘foos’ (plural). but as the addfoo function returns a value, how could that be mapped over. The following works, but are there any other ways?
def addfoos(mydict, foos):
for foo in foos:
mydict = addfoo(mydict,foo)
return mydict
makemany = partial(addfoos, defaultdict(set))
foos = { ('foo','bar',1),
('bar','baz',0) }
mydict = makemany(foos)
print(mydict)
# defaultdict(<class 'set'>, {'baz': {('bar', 0)}, 'foo': {('bar', 1)}, 'bar': {('foo', 1), ('baz', 0)}})
As it is, it works… but I am curious if python has a fmap or similar.
OK… for anyone stumbling across this — use reduce!
the following, although with different variables is exactly what I was aiming for:
from collections import defaultdict
from functools import partial
from functools import reduce
def addnode(graph, node):
x,y,z = node
graph[x].add((y,z))
graph[y].add((x,z))
return graph
def addnodes(graph, nodes):
return reduce(addnode, nodes, graph)
graphnode = partial(addnode, defaultdict(set))
graphnodes = partial(addnodes, defaultdict(set))
and now, either function (addnode or addnodes) can be called to update the dict.
You want
reduce, notmap, since you’re reducing the inputs to a single result, rather than transforming them one-to-one to a list of results.That was python 2.6. Python3 version works the same, but
reduceis infunctoolsnow: