using map or similar to update a dictionary when not using a class

When one is not using methods, what is the best, way to achieve the following.

  1. have a single function for adding items to a dictionary
  2. use that function when adding multiple items to the dictionary
  3. 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
    return mydict

makemydict = partial(addfoo, defaultdict(set))

foo = ('foo','bar',1)

mydict = makemydict(foo)

# 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)

# 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
    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, not map, since you're reducing the inputs to a single result, rather than transforming them one-to-one to a list of results.

>>> reduce(addfoo, foos, defaultdict(set))
defaultdict(<type 'set'>, {'baz': set([('bar', 0)]), 'foo': set([('bar', 1)]), 'bar': set([('foo', 1), ('baz', 0)])})

That was python 2.6. Python3 version works the same, but reduce is in functools now:

>>> from functools import reduce
>>> reduce(addfoo, foos, defaultdict(set))
defaultdict(<class 'set'>, {'baz': {('bar', 0)}, 'foo': {('bar', 1)}, 'bar': {('foo', 1), ('baz', 0)}})

Need Your Help

UIImageView setImage does not work for IBOutlet

ios xcode uiimageview interface-builder iboutlet

I want to set an image as my background at runtime, so I created a UIImageView 'backGroundImage' as IBOutlet in Interface Builder. However the following code: