Dictionary array checks in python

I have 2 dictionaries with arrays. I want the dictionary from the primary list only if 'buckets' show up in the secondary list of dictionary 'buckets' while 'labels' are a match.

primary = [{'buckets': [165, 27],
   'label': 'Andrew'}, {'buckets': [1364],
   'label': 'Matt'},{'buckets':[500, 60, 888], 'label':'John'}]

secondary = [{'buckets': [165, 1447],
  'label': 'Andrew'}, {'buckets': [1365, 15, 16],
  'label': 'Matt'}, {'buckets':[12,10,15], 'label':'Max'}]

data = {}

for x in primary:
    found = False
    for i in secondary:

        for num in x['buckets']:
            if x['label'] == i['label']:
                if num in i['buckets']:
                    found =True
                    break
    if found:
        data[x['label']] = x['buckets']
    else:
        data[i['label']] = i['buckets']

pprint.pprint(data)

If I change the matches around/ numbers in the array I do not get the right results. Any help would be greatly appreciated.

Desired output:
{'Andrew': [165, 27], 'Matt': [1365, 15, 16]}

This occurs sometimes but if i change Andrews numbers in secondary It may end up just this.

{'Matt': [1365, 15, 16]}
728x90

1 Answers Dictionary array checks in python

Here is a solution. The major point which I use here is intersection to check if there is a common value between two lists. If there is, then I take the list from primary. If not, then you take the list from secondary as you explained in the comment below. You don't need a found tag now

data = {}

for x in primary:
    for i in secondary:
        if x['label'] == i['label']:
            if list(set(x['buckets']).intersection(i['buckets'])):
                    data[x['label']] = x['buckets']
                    break
            else:
                data[x['label']] = i['buckets']

print(data)
# {'Andrew': [165, 27], 'Matt': [1365, 15, 16]}

1 weeks ago