coding180 icon
Coding180
Python Dictionaries: Introduction, creation, accessing and modifying values, looping through diction

Python Dictionaries: Introduction, creation, accessing and modifying values, looping through diction

Home > Tutorials > Python for beginners > Data structure


If you're new to programming, the concept of dictionaries may seem confusing at first. But don't worry; once you understand how they work, you'll find that they're a powerful tool for organizing and manipulating data in your Python programs.

What are Python Dictionaries?

In Python, a dictionary is an unordered collection of key-value pairs. Each key is unique and maps to a specific value. Think of it like a real-world dictionary, where each word (key) has a definition (value).

Here's an example of a simple Python dictionary:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

In this case, name, age, and city are the keys, and 'John', 30, and 'New York' are their corresponding values.

Creating Python Dictionaries

To create a dictionary in Python, you can use curly braces {}, with key-value pairs separated by commas. For example:

empty_dict = {}    # an empty dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

You can also create a dictionary using the built-in dict() function:

my_dict = dict(name='John', age=30, city='New York')

This creates the same dictionary as the previous example.

Accessing and Modifying Values in Python Dictionaries

To access the value of a specific key in a dictionary, you can use square brackets [] and the key name. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

print(my_dict['name'])    # output: John

You can also modify the value of a specific key in a dictionary by using square brackets [] and assigning a new value to it. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

my_dict['age'] = 31

print(my_dict)    # output: {'name': 'John', 'age': 31, 'city': 'New York'}

Looping Through Python Dictionaries

You can loop through a dictionary using a for loop and the items() method. The items() method returns a list of key-value pairs as tuples. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

for key, value in my_dict.items():
    print(key, value)

This will output:

name John
age 30
city New York

 

Common Dictionary Methods in Python

Python provides several built-in methods for manipulating dictionaries. Here are some examples:

clear()

The clear() method removes all key-value pairs from a dictionary.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

my_dict.clear()

print(my_dict)    # output: {}

copy()

The copy() method returns a shallow copy of a dictionary.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

new_dict = my_dict.copy()

print(new_dict)    # output: {'name': 'John', 'age': 30, 'city': 'New York'}

pop()

The pop() method removes and returns the value associated with a specified key.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

age = my_dict.pop('age')

print(age)        # output: 30
print(my_dict)    # output: {'name': 'John', 'city': 'New York'}

update()

The update() method updates a dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs.

my_dict = {'name': 'John', 'age': 30}

my_dict.update({'city': 'New York'})

print(my_dict)    # output: {'name': 'John', 'age': 30, 'city': 'New York'}

Exercises

  1. Create a dictionary named car with the following keys and values: `'brand': 'Honda', 'model': 'Civic', 'year': 2022`.
  2. Access the value associated with the key 'model' in the car dictionary and print it to the console.

  3. Modify the value associated with the key 'year' in the car dictionary to 2023.

  4. Loop through the car dictionary and print each key-value pair to the console.

  5. Create a new dictionary named person with the following keys and values: 'name': 'Jane', 'age': 25, 'city': 'San Francisco'.

  6. Use the update() method to add the key-value pair 'profession': 'Software Engineer' to the person dictionary.

  7. Use the pop() method to remove the key-value pair associated with the key 'city' from the person dictionary.

  8. Clear all key-value pairs from the person dictionary using the clear() method.

  9. Congratulations! You now have a solid understanding of Python dictionaries and how to work with them. Keep practicing by creating your own dictionaries and using the built-in methods to manipulate them. Happy coding!


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel