41 lines
1.2 KiB
Plaintext
41 lines
1.2 KiB
Plaintext
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
|
|
|
|
[source,python,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
{"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
|
|
|
|
[source,python,diff-id=1,diff-type=compliant]
|
|
----
|
|
{"one": 1, "two": 2, "three": 3}
|
|
|
|
def func(a1, a2):
|
|
{a1: 1, a2: 2}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* Python Documentation - https://docs.python.org/3/reference/expressions.html#dictionary-displays[Dictionary displays]
|