sundar nataraj
sundar nataraj

Reputation: 8702

Dynamically join of dictionary

a="90342"

# this used to generate a dict of each char in a and it indexs
modchar=[{i:a.index(i)} for i in a ]

#modchar=[{'9': 0}, {'0': 1}, {'3': 2}, {'4': 3}, {'2': 4}]


# below produce combination now this combination
def combination(x,n):
   return list(itertools.combinations(x,n))

combination(modchar,1)

#output [({'9': 0},), ({'0': 1},), ({'3': 2},), ({'4': 3},), ({'2': 4},)]

combination(modchar,2)

#output [({'9': 0}, {'0': 1}), ({'9': 0}, {'3': 2}), ({'9': 0}, {'4': 3}), ({'9': 0}, {'2': 4}), ({'0': 1}, {'3': 2}), ({'0': 1}, {'4': 3}), ({'0': 1}, {'2': 4}), ({'3': 2}, {'4': 3}), ({'3': 2}, {'2': 4}), ({'4': 3}, {'2': 4})]

combination(modchar,3)
#output [({'9': 0}, {'0': 1}, {'3': 2}), ({'9': 0}, {'0': 1}, {'4': 3}), ({'9': 0}, {'0': 1}, {'2': 4}), ({'9': 0}, {'3': 2}, {'4': 3}),....]

if u look at each result in the list first element is tuple of dict.what i want to do is to combine the dictionary inside the tuple and make it as single dict

i have tried

map(lambda x:dict(x[0],**x[1]),list(itertools.combinations(x,n))) 

above works only for tuple of two dicts.

how can i produce a code dynamically it should combine all dicts and produce single dict irrespictive of n value in combination(x,n)

expected output: for n=2

[({'9': 0,'0': 1}) ....]

expected output: for n=3

[({'9': 0,'0': 1,'3': 2})..]

Upvotes: 1

Views: 145

Answers (2)

Brionius
Brionius

Reputation: 14118

Here's a way to do it:

combos = combinations(modchar,3)

def combineDictTuple(dt):
    d = {}
    for item in dt:
        d.update(item)
    return d

newCombos = [combineDictTuple(dt) for dt in combos]

# OUTPUT:  [{'9': 0, '0': 1, '3': 2}, {'9': 0, '0': 1, '4': 3}, {'9': 0, '0': 1, '2': 4}, {'9': 0, '3': 2, '4': 3}, {'9': 0, '3': 2, '2': 4}, {'9': 0, '2': 4, '4': 3}, {'0': 1, '3': 2, '4': 3}, {'0': 1, '3': 2, '2': 4}, {'0': 1, '2': 4, '4': 3}, {'3': 2, '2': 4, '4': 3}]

Upvotes: 1

Alex Shkop
Alex Shkop

Reputation: 2012

This should do what you want:

>>> def update_with_return(d1, d2):
...   d1.update(d2)
...   return d1
... 
>>> reduce(update_with_return, ({'a': 1}, {'b':2}), dict())
{'a': 1, 'b': 2}

Upvotes: 0

Related Questions