To share this page click on the buttons below;
Dictionaries
Dictionaries associates a unique key with a certaing value.
Keys must be immutable types (string, number, tuple).
Empty dictionaries are created with
<mydict> = {}
# or
<mydict> = dict()
Dictionaries with elements can be created with
<mydict> = dict(<key1>: <value1>, <key2>: <value2>, ... , <keyn>: <valuen> )
Lenght
To get the number of elements (pair: key, value) of a dictionary
len(<mydict>)
Items
To get all the pairs (key, value) as a list of tuples
<mydict>.items()
Keys
To get all the keys as a list
<mydict>.keys()
Values
To get all the values as a list
<mydict>.values()
Key presence
To verify if a key is present into a dictionary use the in keyword: (<key> in <mydict>) is true if the <key> actually present into the dictonary <mydict>
Access a key that is not present in the dictonary causes a KeyError.
Add
To add <value> with <key> in <mydict> use <mydict>[<key>] = <value>
Get
To get the <value> corresponding to the <key> use <mydict>[<key>].
If <key> does not exist an error is thrown.
Using the function <mydict>.get(<key>) will return the <value> or None if the <key> is not defined.
Remove
To remove all elements from a dictionary use <mydict>.clear().
To remove an element with a certain key use <mydict>.pop(<key>) (this returns the value removed).
To remove the last inserted item in the dictionary use <mydict>.popitem() (this returns the value removed).
To share this page click on the buttons below;