Python Dictionary of Dictionary with condition
I am working on a function. If "source" is found in "d" then it will be added to it's value of dictionary object, otherwise it will be added. For example in this case. "a" is added twice but "b" is added once.
I would like to get output as below(last line)
Thank you.
def adder(source,dest,weight):
""""""
if __name__ == "__main__":
d = {} #dictionary
adder('a','b',1)
adder('a','f',4)
adder('b','c',1)
adder('f','g',3)
print d
{'a':{'b':1,'f':4}, 'b':{'c':1},开发者_开发问答 'f':{'g':3},g:{},c:{}} #<----final o/p needed
A dictionary of dictionaries is just a dictionary of tuples. You could implement adder like this:
#The dictionary we will be adding to
d = {}
def adder(source, dest, weight):
d[(source, dest)] = weight
The high brow reason for this is that in any category with products, Hom(C, Hom(B, A)) is naturally isomorphic to Hom(C x B, A). Or in a functional language,
f : C -> (B -> A)
Is the same as:
f : C x B -> A
And coincidentally, it is also why (A^B)^C = A^(B * C).
The following implementation should do so:
def adder(dict, source, dest, weight):
if not source in dict:
dict[source] = {}
if not dest in dict:
dict[dest] = {}
dict[source][dest] = weight
Please note that I added dict
as first argument to your method.
You can just use a simple if condition:
In [9]: def adder(d,source,dest,weight):
...: if source in d:
...: d[source][dest] = weight
...: else:
...: d[source] = {dest: weight}
...:
In [10]: d={}
In [11]: adder(d, 'a', 'b', 1)
In [12]: adder(d, 'a', 'f', 4)
In [13]: adder(d, 'b', 'c', 1)
In [14]: d
Out[14]: {'a': {'b': 1, 'f': 4}, 'b': {'c': 1}}
精彩评论