Home > Software engineering >  Flag duplicate keys in dictionary using pylint
Flag duplicate keys in dictionary using pylint

Time:09-01

Is there a static code analysis tool that can flag duplicate keys in a python dictionary?

Context: I use large dictionary to capture tasks in a scheduler. If mistakenly key name for two tasks are the same then the 2nd item replaces the 1st item silently and we lose one task in the the schedule.

I was hoping if we can flag this duplicate key using code analysis (lint).

Code example:

d = {'a': 1,'b': 2, 'a': 3}
print(d.items())

>>dict_items([('a', 3), ('b', 2)])

CodePudding user response:

To solve this problem, I would recommend using a priority queue.

The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data). queue

CodePudding user response:

pylint has duplicate-key. Result on your code example:

************* Module a
a.py:1:4: W0109: Duplicate key 'a' in dictionary (duplicate-key)
  • Related