org.sonar.l10n.py.rules.python.S5780.html Maven / Gradle / Ivy
This rule raises an issue when the same key is used multiple times when instantiating a dictionary literal.
Why is this an issue?
By definition, a dictionary cannot hold the same key multiple times. When instantiating a dictionary literal, if a key is repeated, only the last
occurrence of the key will be retained.
This can lead to errors and confusion, as it is not clear which value belongs to which key. This can be remedied by either:
- replacing the duplicated key with the correct key to prevent bugs and errors from occurring later in the program.
- removing the duplicated key to make the code more concise and easier to maintain.
Code examples
Noncompliant code example
{"one": 1, "two": 2, "one": 3} # Noncompliant: the key "one" is duplicated.
def func(a1, a2):
{a1: 1, a2: 2, a1: 3} # Noncompliant: the key a1 is duplicated.
Compliant solution
{"one": 1, "two": 2, "three": 3}
def func(a1, a2):
{a1: 1, a2: 2}
Resources
Documentation
- Python Documentation - Dictionary displays
© 2015 - 2024 Weber Informatics LLC | Privacy Policy