Juanvulcano
Juanvulcano

Reputation: 1396

Merging keys on a dictionary - Python

I want to use the minimun cuts algorithm in a python's graph such that:

 { 1 : [5, 8, 10], 2 :[3, 8, 9] } == { 1 : [5, 8, 10, 3, 9] }

What is the more pythonic way of merging the dictionaries?

Upvotes: 1

Views: 88

Answers (3)

Malik Brahimi
Malik Brahimi

Reputation: 16721

You can import operator then reduce the dictionary values by adding them to one another like so

set(reduce(operator.add, d.values())) # the set of each successive value added to the next

Upvotes: 2

j-i-l
j-i-l

Reputation: 10997

If you have two lists:

a = [5, 8, 10]
b = [3, 8, 9]

You can merge them with minimum cut policy like so:

list(set(b) | set(a))

If you want to do the operation in place, use:

a[:] = list(set(b) | set(a))

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

You can use set.union to get the unique values then convert it to set and get the minimum key with min function :

>>> {min(d.keys()):list(set().union(*d.values()))}
{1: [8, 9, 10, 3, 5]}

Upvotes: 1

Related Questions