get values from dict whose key values match another dict

Question:

I have two dicts whose values are themselves dicts. I would like to create another dict whose values are the values from dict2 that have the same ‘asin’ key value as dict1. I have example output below. I haven’t worked with dicts that much so any tips are greatly appreciated.

Code:

dict1
    
{0:[{u’asin’: u’a’, u’h’: u’b’},{u’asin’: u’b’, u’h’: u’c’}], 1:[{u’asin’: u’c’, u’h’: u’b’},{u’asin’: u’d’, u’h’: u’c’}, 2:[{u’asin’: u’d’, u’h’: u’f’},{u’asin’: u’k’, u’h’: u’c’}]}

Code:

dict2
    
{0:{u’asin’: u’f’, u’img’: u’123’}, 1:{u’asin’: u’c’, u’img’: u’eed’}, 2:{u’asin’: u’d’, u’img’: u’ffg’}}

Desired Output:

{1:{u’asin’: u’c’, u’img’: u’eed’}, 2:{u’asin’: u’d’, u’img’: u’ffg’}}
Asked By: user3476463

||

Answers:

You can use itertools.chain to merge all sub-lists in dict1 first before using list comprehension to filter dict2.

from itertools import chain
dict1 = {0:[{'asin': 'a', 'h': 'b'},{'asin': 'b', 'h': 'c'}], 1:[{'asin': 'c', 'h': 'b'},{'asin': 'd', 'h': 'c'}], 2:[{'asin': 'd', 'h': 'f'},{'asin': 'k', 'h': 'c'}]}
dict2 = {0:{'asin': 'f', 'img': '123'}, 1:{'asin': 'c', 'img': 'eed'}, 2:{'asin': 'd', 'img': 'ffg'}}
r = {d['asin'] for d in chain(*dict1.values())}
print({k: v for k, v in dict2.items() if v['asin'] in r})

This outputs:

{1: {'asin': 'c', 'img': 'eed'}, 2: {'asin': 'd', 'img': 'ffg'}}
Answered By: blhsing

You can use a couple of comprehensions: a set comprehension to extract all keys from values of d1, and a dictionary comprehension to filter items in d2.

keys = {subdict['asin'] for item in d1.itervalues() for subdict in item}

d3 = {k: v for k, v in d2.iteritems() if v['asin'] in keys}

print(d3)

{1: {'asin': 'c', 'img': 'eed'}, 2: {'asin': 'd', 'img': 'ffg'}}

In Python 3.x, replace itervalues / iteritems with values / items.

Answered By: jpp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.