-2
length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4} 
count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}

intersection = length_word.items() - count_word.items() 
common_words = {intersection}

Err: TypeError: unhashable type: 'set'

I wish to get this dictionary:

outcome = {'pen':10, 'bird':50, 'computer':3, 'mail':12}

Thanks.

Pygirl
  • 12,969
  • 5
  • 30
  • 43
A A
  • 3
  • 2
  • A set as an unhashable type can not be part of an other set nor a key in a dictionary. – Klaus D. Mar 10 '21 at 17:33
  • See this post, it answers your question: https://stackoverflow.com/questions/18554012/intersecting-two-dictionaries-in-python – sander Mar 10 '21 at 17:37

5 Answers5

0
intersection = count_word.keys() & length_word.keys()    

outcome = dict((k, count_word[k]) for k in intersection)
moe9195
  • 11
  • 1
  • 1
0

try getting the intersection (common keys). one you have the common keys access those keys from the count_words.

res = {x: count_word.get(x, 0) for x in set(count_word).intersection(length_word)}

res:

{'bird': 50, 'pen': 10, 'computer': 3, 'mail': 12}
Pygirl
  • 12,969
  • 5
  • 30
  • 43
  • Why use `get` with a default rather than `count_word[x]`? – superb rain Mar 10 '21 at 17:51
  • @superbrain: Yes actually If you are going for union thing then use `get`. For this case it's not required to use get so yeah one can use directly also. – Pygirl Mar 10 '21 at 17:55
0

Using for loop check if the key is present in both the dictionary. If so then add that key, value pair to new dictionary.

length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4}
count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}
my_dict = {}

for k, v in count_word.items():
    if k in length_word.keys():
        my_dict[k] = v

print(my_dict)
Rima
  • 1,447
  • 1
  • 6
  • 12
0

You should use .keys() instead of .items(). Here is a solution:

length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4}
count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}
intersection = count_word.keys() & length_word.keys()    

common_words = {i : count_word[i] for i in intersection}

#Output: 
{'computer': 3, 'pen': 10, 'mail': 12, 'bird': 50}

Inputvector
  • 1,061
  • 10
  • 22
0

Just another dict comp:

outcome = {k: v for k, v in count_word.items() if k in length_word}
superb rain
  • 5,300
  • 2
  • 11
  • 25