Merge Two Dictionaries that Share Same Key:Value

Saigo no Akuma

I know this can be done with lists, but I'm just trying to figure out how to do this with dictionaries.

Basically, it'll go like this:

dict1 = {'a': 10, 'b': 12, 'c': 9}
dict2 = {'a': 10, 'b': 3, 'c': 9}

def intersect(dict1, dict2):
    combinDict = dict()


....
print(combinDict)
{'a': 10, 'c':9}

So I only want the keys with the same value added into a new dictionary.

Any help?

Padraic Cunningham

You want the intersection of the items:

dict1 = {'a': 10, 'b': 12, 'c': 9}
dict2 = {'a': 10, 'b': 3, 'c': 9}

print dict(dict1.viewitems() & dict2.items())
{'a': 10, 'c': 9}

For python 3 you just want to use items:

 dict(dict1.items() & dict2.items())

dict1.items() & dict2.items() returns a set of key/value pairings that are common to both dicts:

In [4]: dict1.viewitems() & dict2.items()
Out[4]: {('a', 10), ('c', 9)}

Then we simply call the dict constructor on that.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Merge two python dictionaries on the same key and value

merge two dictionaries with same key values

How to merge two dictionaries with same key names

Merge a single list of dictionaries with the same key value

Merge dictionaries if value of a particular key is same

merge two dataframe that share the same column value

merge two dictionaries by key

Python: Most elegant way to merge two dictionaries with the same key

NSArray of NSDictionaries - merge dictionaries with same key value pair

Match key and value from two different dictionaries and merge them

How can I merge two dictionaries with multiple key value pairs

How to merge lists value with shared key of two dictionaries?

Merging two or more dictionaries when they have the same key value pairs

How to merge multiple dictionaries from separate lists if they share any key-value pairs?

Merge if key value are the same?

Merge dictionaries if of the object key values is the same in python

Merge two dictionaries based on similarity excluding a key

Merge two dictionaries in Python with the same keys

How to merge two Dictionary in python with same key but different value

How to merge two list of dicts if value of key is the same?

Rails: How to merge two hashes if a specific key has the same value?

Map an Array and check for a specific key if it has the same value then merge the two

How to merge values of dictionaries with same key into one from a list of dictionaries?

How to merge list of dictionaries by unique key value

Dynamically merge lines that share the same key into one

merge two tuples with same key

Merge two dicts by same key

merge two dictionary with same key

Merge two columns of a dataframe into an already existing column of dictionaries as a key value pair

TOP Ranking

HotTag

Archive