fbpx
1- Introduction
2- Python Basic
3- Learning Python
4- Python Literals
5- Arithmetic operators
6- Function INPUT() and STRING operations
7- Comparison Operators and Conditions
8- Loops in Python
9- Logic and bit operators
10- Lists and Arrays in Python
11- Functions
12- Tuples, Dictionaries
13- Conclusion
14- Practice Exams

L12.2 Dictionaries

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered (only in python 3.7 & above), changeable and does not allow duplicates. A dictionary is surrounded by curly braces, while the pairs in the dictionary are separated by commas, and pair’s keys and values by colons.

Example 1:

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
print(dictionary)

In above example, a key-value pair is created for each animal wherein cat like milk, dog likes bone and horse likes grass. Note that key-value pair in this example are string but it can be string or number as you can see in next example.

Example 2:

phone_numbers = {'boss': 5551234567, 'Suzy': 22657854310}
print(phone_numbers)

Example 3:

car_dict= {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(car_dict["brand"])

We hope you are not confused with the way we defined dictionary in example 1 and example 3. 😉

Of course, example 3 is a better way to define dictionary. Such ways of formatting code is called hanging indents.

Note:

  • each key must be unique – it’s not possible to have more than one key of the same value;
  • a key may be any immutable type of object: it can be a number (integer or float), or even a string, but not a list;
  • a dictionary is not a list – a list contains a set of numbered values, while a dictionary holds pairs of values;
  • the len() function works for dictionaries, too – it returns the numbers of key-value elements in the dictionary;
  • a dictionary is a one-way tool – you can look up a value of key but not the key of value.
  • keys are case-sensitive'Apple' is something different from 'apple'.

Reading a dictionary

To read a dictionary, you need to pass a valid key. See example below.

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
phone_numbers = {'boss' : 5551234567, 'Suzy' : 22657854310}
empty_dictionary = {}

print(dictionary['cat'])
print(phone_numbers['Suzy'])

To search a particular value in a dictionary, try below script

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
words = ['cat', 'lion', 'horse']

for word in words:
    if word in dictionary:
        print(word, "->", dictionary[word])
    else:
        print(word, "is not in dictionary")

To retrieve key-value pair from a dictionary, use the keys() method. Try below code.

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
for key in dictionary.keys():
    print(key, "->", dictionary[key])

If you want to sort the output, use sorted() method. Try below code

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
for key in sorted(dictionary.keys()):
    print(key, "->", dictionary[key])

There is another way to return the key-value pair which is by using items() method.

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
for animal, food in dictionary.items():
    print(animal, "->", food)

The following example will help you return values in a dictionary by using values() method.

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
for food in dictionary.values():
    print(food)

The below example returns a dictionary item using get() method.

dictionary = {
    "cat": "milk",
    "dog": "bone",
    "horse": "grass"
    }

item_2 = dictionary.get("cat")
print(item_2)    

Adding and modifying dictionaries

Dictonaries are mutable which means we can add or change the key-value pairs.

Here is how to change the value of a key:

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
dictionary['cat'] = 'meat'
print(dictionary)

Here is how to add a new key-value pair in a dictionary.

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
dictionary['lion'] = 'meat'
print(dictionary)

Did you notice the difference in both examples? 😎

Here is how to remove a key.

dictionary = {"cat": "milk", "dog": "bone", "horse": "grass"}
del dictionary['dog']
print(dictionary)

Here is another example showing how to use del, clear() method to delete an item, clear all items and delete the whole dictionary.

dictionary = {
    "cat": "milk",
    "dog": "bone",
    "horse": "grass"
    }


print(len(dictionary))    # outputs: 3
del dictionary["cat"]    # remove an item
print(len(dictionary))    # outputs: 2

dictionary.clear()   # removes all the items
print(len(dictionary))    # outputs: 0

del dictionary    # removes the dictionary

Note: You can use del method to delete a tuple too.

To copy a dictionary, use the copy() method:

dictionary = {
    "cat": "milk",
    "dog": "bone",
    "horse": "grass"
    }

copy_dictionary = dictionary.copy()
print (copy_dictionary)

0
Wanna ask a question or say something? Go aheadx
()
x
Scroll to Top