简体   繁体   中英

Finding the difference between keys and values in the same dictionary

I have a dictionary with similar keys and values, and I am looking to find the keys that do not appear in the values within the dictionary.

This is my output when I print my dictionary, d1 :

d1= {"A": ["J"], "B": ["A"], "C": ["A", "D", "J"], "D": ["A", "J"]}

From the code above, the keys "B" and "C" would be the two keys that do not appear in the values, and I would like to be able to print them out in a list.

This is my code:

keysNotInValues = []
d1_keys = (d1.keys())

for key in d1_keys:
    flag = True
    for keys,values in d1.items():
        if key in values:
            flag == False

    if flag == True:
        keysNotInValues.append(key)

print(keysNotInValues)

My output that I received is simply a list of all the keys.

['A', 'B', 'C', 'D']

I am wanting the output:

['B', 'C']

You can use sets to work out the difference between 2 collections

keys = set(d1)
values = set(item for sublist in d1.values() for item in sublist)
print(keys - values)  # {'C', 'B'}

I think the nature of your problem is you reset flag=True upon each loop iteration. With that code structure, you don't find "keys that are in none of the values", you instead find "keys that are missing from at least one of the values". Since every key is missing from at least one of the values, your function returns all keys.

One way to do this is with Python's built-in set() object, using the set arithmetic methods that are built-in:

d1 = {"A": ["J"], "B": ["A"], "C": ["A", "D", "J"], "D": ["A", "J"]}

set_of_keys = set(d1.keys())

set_of_values = set()
for vals in d1.values():
    set_of_values.update(vals)

print(set_of_keys)
print(set_of_values)

values_that_arent_keys = set_of_values - set_of_keys
print(values_that_arent_keys)

keys_that_arent_values = set_of_keys - set_of_values
print(keys_that_arent_values)

Gives:

{'D', 'C', 'B', 'A'}
{'J', 'D', 'A'}
{'J'}
{'C', 'B'}

You can use sorted() if you want to have your sets printed alphabetically.

d1 = {"A": ["J"], "B": ["A"], "C": ["A", "D", "J"], "D": ["A", "J"]}
list1 = []
d2 = d1.keys()
d3 = d1.values()

for a in d2:
    flag = True
    for b in d3:
        if a in b:
            flag = False
    if flag == True:
        list1.append(a)
print(list1)

Just did a little modification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM