Reputation: 81
Hi i need to get my program to display only the values that appear as keys and never as values in a dictionary?
i tried and got the values and keys stored in a dictionary and now i don't know how to identify the one that is only a key and never a value
lets say i have dict[('1', '2'), ('1', '3'), ('2', '4'), ('3', '4'), ('5', '6')]
now the only item that only appears as a key and not a value is 1 and 5 so how do i get my program to display
only a key not a value:
1
5
Upvotes: 0
Views: 1192
Reputation: 251558
You can do
set(d.keys()) - set(d.values())
Note that your example has a problem (apart from the syntax mistake). You have two tuples with '1'
as the first element. A dict can't have the same key twice. The second one will override the first, so ('1', '2')
will not make it into the dict, and so '2' is also a key that does not occur as a value.
Upvotes: 3
Reputation: 32197
Why not iterate through the dict
as follows:
allowed = [i for i in my_dict if i not in my_dict.values()]
Upvotes: 0