Reputation: 159
I want to create a set of dictionaries in python. I know how to make a list of dictionaries and convert it to set, but I want to add a dictionary to a set. Can anyone help me? I got this error when I try below code: "Exception has occurred: TypeError unhashable type: 'dict'"
C = set()
A = {'a':1, 'c':2, 'd':3}
B = {'c':3, 'd':4, 2:5 }
C.add(A)
C.add(B)
Thanks
Upvotes: 1
Views: 709
Reputation: 685
For the below:
C = set()
A = {'a':1, 'c':2, 'd':3}
B = {'c':3, 'd':4, 2:5 }
You could do something like this to combine all the above into a single set. I will use an union operator '|' to achieve this.
{i for i in A.items()} | {i for i in B.items()}
This results to:
{('a', 1), ('c', 2), ('c', 3), ('d', 3), ('d', 4), (2, 5)}
** Extra Information **
If you knew from the start that dictionary B does not contain any of the keys found in dictionary A, you could do something like the below to combine the two dictionaries:
For example:
A = {'a':1, 'c':2, 'd':3}
B = {'e':3, 'f':4, 2:5 }
from collections import Counter
C = Counter(A) + Counter(B)
C equates to the below:
Counter({'a': 1, 'c': 2, 'd': 3, 'e': 3, 'f': 4, 2: 5})
Upvotes: 1