In Python, a dictionary is an ordered (from Python > 3.7) collection of key
: value
pairs.
[]
[]
In case the key is not present in dictionary KeyError
is raised.
values()
The values()
method gets the values of the dictionary:
keys()
The keys()
method gets the keys of the dictionary:
There is no need to use .keys() since by default you will loop through keys:
items()
The items()
method gets the items of a dictionary and returns them as a <router-link to=/cheatsheet/lists-and-tuples#the-tuple-data-type>Tuple</router-link>:
Using the keys()
, values()
, and items()
methods, a for loop can iterate over the keys, values, or key-value pairs in a dictionary, respectively.
get()
The get()
method returns the value of an item with the given key. If the key doesn't exist, it returns None
:
You can also change the default None
value to one of your choice:
setdefault()
It's possible to add an item to a dictionary in this way:
Using the setdefault
method, we can make the same code more short:
del
The del
method removes an item based on a given key.
A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries.
There are two ways to create sets: using curly braces {}
and the built-in function set()
When creating set, be sure to not use empty curly braces
{}
or you will get an empty dictionary instead.
A set automatically remove all the duplicate values.
And as an unordered data type, they can't be indexed.
add()
and update()
Using the add()
method we can add a single element to the set.
And with update()
, multiple ones:
remove()
remove()
will raise a key error
if the value doesn't exist.
union()
union()
or |
will create a new set that with all the elements from the sets provided.
intersection()
intersection
or &
will return a set with only the elements that are common to all of them.
difference()
difference
or -
will return only the elements that are unique to the first set (invoked set).
symetric_difference()
symetric_difference
or ^
will return all the elements that are not common between them.