How do I check to see if values in a dict are the exact same?

Viewed 148

I currently have a dictionary d with key: string, and values is another dict.

In the d dictionary values, how can I check which key and values are ALL the same?


Example Dictionary:

zybook, zybooks, zybookz are keys. There can be more than three keys, but I only put two for now. And then the values of d are another dict with {file name : number}

d = {"zybook": 
        {
         "noodle.json": 5,
         "testing.json": 1,
         "none.json": 5
        },
    "zybooks": 
        {
         "noodle.json": 5,
         "ok.json": 1
        },
    "zybookz":
        {
         "noodle.json": 5
        }
    }

Expected Output:

Because {"noodle.json": 5} {"noodle.json": 5} are both the same in zybook, zybooks, and zybookz the output will create another dictionary with all 3 matches.

{"noodle.json": 5}

My attempt:

I honestly don't know how to approach this.

d = {"zybook": { "noodle.json": 5, "testing.json": 1, "none.json": 5},
    "zybooks": {"noodle.json": 5, "ok.json": 1},
    "zybookz": {"noodle.json": 5}
}

for key, value in d.items():
    for k, v in value.items():
        if     
3 Answers

Try this:

from collections import Counter

res = {z[0]: z[1] for z, count in Counter([(k, v) for x in d for k, v in d[x].items()]).items() if count == len(d)}
from functools import reduce
sets = (set(val.items()) for val in d.values())
desired = dict(reduce(set.intersection, sets))
print(desired)
# {'noodle.json': 5}

We first form sets out of the file_name:num pairs of each dictionary. Then, reduce cumulatively looks each set and reduces them to the desired result by taking intersection of those sets. Lastly, converting to a dict as needed.

With only the use of embedded Python methods

new = []
for v in d.values():
    new+=list(v.items())
# [('noodle.json', 5), ('testing.json', 1), ('none.json', 5), ('noodle.json', 5), ('ok.json', 1)]

cnt_dict = {v:new.count(v) for v in new}
# {('noodle.json', 5): 3, ('testing.json', 1): 1, ('none.json', 5): 1, ('ok.json', 1): 1}

d2 = {k[0]:k[1] for k,v in cnt_dict.items() if v > 1}
print(d2)
# {'noodle.json': 5}
Related