Reputation: 185
My code is something like:
d = defaultdict(list)
for prod_no ,production in enumerate(productions):
cp = Production(*productions[prod_no])
count_yields = len(cp.pattern_list())
#temp.setdefault(temp[cp.lhs()], []).append(count_yields)
d[cp.lhs()].append(count_yields)
print d
As an output I am getting something like given below:
defaultdict(<type 'list'>, {'A': [3, 3, 4, 3], 'S': [1], 'B': [4,5]})
Now I need to report an error because key 'A' has different multiple values like 3 and 4. Same can be said about key 'B'.
There should not be any error if I am getting an output like
defaultdict(<type 'list'>, {'A': [3, 3, 3, 3], 'S': [1]})
because both 'A' and 'S' has same values throughout...
Upvotes: 0
Views: 125
Reputation: 44444
If you want to check for duplicates in a list(acc. to the title), you could convert it into a set and check for its length (in this case, 1):
if not all(len(set(items))==1 for items in d.values()):
#A list against some key does not have all-same elements.
Upvotes: 2
Reputation: 10695
I can't quite make out the Python syntax in your example, so I'll answer you based on two different ideas.
What you want to do depends on when you want to do it. For example, if you want to prevent a duplicate value, then here is one way to do that:
x_set = {'A':[4, 3]}
incoming_val = 3
if incoming_val in x_set['A']:
print("The incoming value already present.")
If you want to eliminated duplicate values after error reporting, you could do the following:
>>> x_set
{'A': [4, 3, 3]}
>>> list(set(x_set['A']))
[3, 4]
>>>
You could also put the list append attempt in a try .. catch and signal an exception and catch it. That is also a Pythonic thing to do.
Upvotes: 0
Reputation: 345
if d is the dictionary (it can be any dictionary including the default dictionary). You can use the following code. This will check for repetitions in the dictionary
for i in d.values():
if len(set(i)) != len(i):
print str(i) + " error"
Upvotes: 0
Reputation: 287885
You should use sets instead of lists as the value of your dictionary if you don't want duplicate values. In any case, you can check for duplicate values with
dct = {'A': [4,3,3,3], 'S': [1]}
if any(len(v) != len(set(v)) for v in dct.values()):
raise ValueError('Duplicate values in an item list')
Upvotes: 2