What is the difference between a dictionary and a set in Python?
In Python, a dictionary and a set are both data structures that store collections of items, but they have some key differences:
Keys and values: A dictionary is a collection of key-value pairs, where each key is associated with a value, while a set is simply a collection of unique elements.
Mutable vs Immutable: A dictionary is a mutable data type, which means its contents can be changed after it is created, while a set is also mutable, but its individual elements are immutable.
Accessing elements: In a dictionary, you can access a value by its key, whereas in a set, you can access elements directly, but not by any key.
Duplication: Dictionaries allow for duplicate values for different keys, while sets do not allow duplicates.
Here's an example to illustrate the difference between a dictionary and a set:
person'
with keys '"name"'
, '"age"'
, and '"city"'
, and values '"John"'
, '30'
, and '"New York"'
, respectively. We also create a set called fruits
with elements "apple"
, '"banana"'
, '"orange"'
, and '"apple"'
(note that the second '"apple"'
is ignored because sets do not allow duplicates).We can access the value associated with the key '
"name"'
in the 'person'
dictionary using 'person["name"]'
, but we cannot do the same with the set 'fruits'
. Instead, we can check if the element '"banana"'
is in the set using the in
keyword.
Comments
Post a Comment