Home > Backend Development > Python Tutorial > Why are values ​​in Python dictionary not allowed to be repeated?

Why are values ​​in Python dictionary not allowed to be repeated?

coldplay.xixi
Release: 2020-10-29 16:20:23
Original
9599 people have browsed it

The reasons why duplicate values ​​in the python dictionary are not allowed are: 1. There is a clear principle that each key can only correspond to one item; 2. When there is a key conflict, the most recent assignment is taken; 3. The key must be hashable.

Why are values ​​in Python dictionary not allowed to be repeated?

The reason why duplicate values ​​in the python dictionary are not allowed is:

There are no restrictions on the values ​​in the dictionary. It can be any Python object, from standard objects to user-defined objects, but the keys in the dictionary are type-restricted.

1. One key is not allowed to correspond to multiple values. One principle must be made clear: each key can only correspond to one item. In other words: multiple values ​​corresponding to one key are not allowed (container objects like lists, tuples, and other dictionaries are allowed). When there is a key conflict (that is, a dictionary key is assigned a value repeatedly), the last (most recent) assignment is taken. Python does not generate an error due to conflicting keys in the dictionary. It does not check for key conflicts because if it did, it would be checked every time a key-value pair is assigned, which would take up a certain amount of time. amount of memory. For example: >>> dict1 = {'foo':789, 'foo': 'xyz'} >>> dict1 Result: {'foo': 'xyz'}

2 , the key must be hashable. Most Python objects can serve as keys, but they must be hashable objects. Mutable types like lists and dictionaries cannot be used as keys since they are not hashable. All immutable types are hashable, so they can be used as dictionary keys.

Related free learning recommendations: python tutorial(Video)

The above is the detailed content of Why are values ​​in Python dictionary not allowed to be repeated?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template