Reputation: 71
I hope to make a dictionary and a list into set then if a.keys() == b
then I will print the a.values()
.
Example:
c = [{'1': '0'}, {'0': '5'},{'2': '0'}]
d = {1,2}
I hope to make these two into the set. Then find all the similarities and print the values without changing the sequence.
Example, I want to print this.
{'1': '0'}
{'2': '0'}
Is it possible to use set?
Below is my code:
a = set(c.keys()) & set(d)
print(a)
for x in a:
y,z = c[x]
Upvotes: 0
Views: 197
Reputation: 5764
First of all, you specified your input values the wrong way. The dictionary c
should be defined as a dictionary with keys and values and not as a list of dictionaries with one item each - as you did. The keys should be specified as integer and not as string. Otherwise you need to cast them from string
to int
later on. The second item d
is specified the wrong way, too. This should be a list of integers and not a dictionary.
Here's the code that specifies the input values correctly and gives you the desired output:
c = {1: '0', 0: '5', 2: '0'}
d = [1,2]
distinct_keys = c.keys() & set(d)
# {1, 2}
distinct_values = {key: value for key, value in c.items() if key in distinct_keys}
# {1: '0', 2: '0'}
distinct_values
This gives {1: '0', 2: '0'}
as output.
Upvotes: 1
Reputation: 106455
Since your example set contains integers while the keys in your example dicts are strings, you should convert the integers in the set to strings first. After that you can simply loop through each dict in the list and if the keys of the dict intersects with the set, then print the dict since it's a match:
d = set(map(str, d))
for i in c:
if i.keys() & d:
print(i)
This outputs:
{'1': '0'}
{'2': '0'}
Upvotes: 3