Python Tutorial Series – Dictionaries

Another type of collection that Python provides support for is dictionaries.

Dictionaries

Dictionaries are used to store comma separated key, value pairs enclosed in curly brackets, example:
to_do_dict = {'a':'groceries', 'b':'laundry', 'c':'wash car', 'd':'vacuum'}

Dictionaries do not have any order and may be changed.
Elements are accessed by using their key value.
For example this would print the third element value in the dictionary, which is 'wash car':
print(to_do_dict['c'])


Dictionaries may be looped through by using the in keyword:
for key in to_do_dict :

    print(key)


Python provides support for many built in dictionary functions. These functions are as follows:

clear - Removes all elements from the dictionary. Example:
to_do_dict.clear()

fromkeys - Creates a dictionary with the given keys having the given value. Example:
to_do_dict.fromkeys('a', 'b', 'c', 1)

copy - Returns a copy of the dictionary. Example:
new_list = to_do_dict.copy()

pop - Removes an item from the dictionary with the input index. Example:
to_do_dict.pop(2)


Another useful Python method for dictionaries is:

len - Returns the number of elements in a dictionary. Example:
num = len(to_do_dict)


More Python





Comments