Difference Between {} and [] in Python

In this tutorial, I will explain the key differences between using curly braces {} and square brackets [] in Python. As a Python developer working on projects for clients in the USA, I’ve encountered situations where choosing the right syntax is important. Let us learn, more about this topic today.

Understand the Basic difference between {} and [] in Python

In Python, {} and [] serve different purposes:

  • {} (curly braces) are used to define dictionaries, which are key-value pairs.
  • [] (square brackets) are used to define lists, which are ordered collections of elements.

Here’s a quick example to illustrate the difference:

# Using {} to create a dictionary
employee = {"name": "John Doe", "age": 35, "city": "New York"}

# Using [] to create a list
cities = ["New York", "Los Angeles", "Chicago", "Houston"]

In the above code, employee is a dictionary that stores information about an employee, while cities is a list of city names in the USA.

Read Python 3 vs Python 2

When to Use {} (Dictionaries)

Dictionaries in Python are very useful when you need to store and retrieve data based on unique keys. They provide fast lookup times and allow you to organize related information effectively. Here are some real-world scenarios where using dictionaries can be beneficial:

Example 1: To Store User Profiles

Suppose you’re building a web application for a company based in the USA, and you need to store user profiles. Each user has a unique username, and you want to associate various pieces of information with each user. Here’s how you can use a dictionary to achieve this:

user_profiles = {
    "johndoe": {"name": "John Doe", "email": "john@example.com", "location": "New York"},
    "janedoe": {"name": "Jane Doe", "email": "jane@example.com", "location": "California"},
    "bobsmith": {"name": "Bob Smith", "email": "bob@example.com", "location": "Texas"}
}

In this example, each username serves as a unique key, and the corresponding value is another dictionary containing the user’s name, email, and location. To access a specific user’s information, you can simply use the username as the key:

print(user_profiles["johndoe"]["email"])  

Output:

john@example.com

I have excited the above example code and added the screenshot below.

Difference Between {} and [] in Python

Read How to Check if a Variable Exists in Python?

Example 2: To Count Word Frequencies

Let’s say you’re working on a project that involves analyzing customer reviews for a product sold in the USA. You want to count the frequency of each word in the reviews to gain insights into customer sentiment. Here’s how you can use a dictionary to accomplish this:

review = "The product is great! I highly recommend it to everyone."

word_count = {}
for word in review.split():
    if word.lower() in word_count:
        word_count[word.lower()] += 1
    else:
        word_count[word.lower()] = 1

print(word_count)

Output:

{'the': 1, 'product': 1, 'is': 1, 'great!': 1, 'i': 1, 'highly': 1, 'recommend': 1, 'it': 1, 'to': 1, 'everyone.': 1}

I have excited the above example code and added the screenshot below.

Difference Between {} and [] in Python To Count Word Frequencies

In this example, we split the review into individual words and use a dictionary to keep track of the count for each unique word. The words serve as keys, and their corresponding counts are the values. This approach allows for efficient counting and easy retrieval of word frequencies.

Read Convert Int to Bytes in Python

When to Use [] (Lists)

Lists in Python are used when you need to store and manipulate ordered collections of elements. They maintain the order of elements and allow for easy insertion, deletion, and iteration. Here are a couple of examples where using lists can be advantageous:

Example 1: Manage a Todo List

Imagine you’re developing a todo list application for users in the USA. Each user has a list of tasks they need to complete. Here’s how you can represent a user’s todo list using a Python list:

todo_list = ["Buy groceries", "Pay bills", "Schedule dentist appointment", "Call mom"]

With a list, you can easily add new tasks, remove completed tasks, or reorder the tasks as needed:

todo_list.append("Pick up dry cleaning")
todo_list.remove("Pay bills")
todo_list[1] = "Schedule doctor appointment"

Lists provide a flexible and intuitive way to manage ordered collections of items, making them perfect for scenarios like todo lists.

Read Difference Between = and == in Python

Example 2: Process Data from CSV Files

Suppose you’re working with data from a CSV file that contains information about sales transactions in different states across the USA. Each row in the CSV file represents a single transaction. Here’s how you can use lists to process and analyze the data:

import csv

with open("sales_data.csv", "r") as file:
    csv_reader = csv.reader(file)
    next(csv_reader)  # Skip the header row

    transactions = []
    for row in csv_reader:
        transaction = [row[0], float(row[1]), row[2]]
        transactions.append(transaction)

# Perform analysis on the transactions list
total_sales = sum(transaction[1] for transaction in transactions)
print(f"Total sales: ${total_sales:.2f}")

In this example, we read data from a CSV file and use a list called transactions to store each transaction as a sublist. Each sublist contains relevant information such as the transaction ID, amount, and state. By storing the data in a list, we can easily perform calculations and analysis, such as calculating the total sales across all transactions.

Read How to Get the Index of an Element in a List in Python?

Comparison between Lists and Dictionaries in Python

To further clarify the differences between lists and dictionaries, let’s compare their key characteristics:

CharacteristicListDictionary
Syntax[]{}
OrderingOrderedUnordered
IndexingBy position (0, 1, 2, …)By unique keys
MutabilityMutable (can be modified)Mutable (can be modified)
DuplicatesAllows duplicate elementsDoes not allow duplicate keys
Common Use Cases– Storing ordered collections
– Iterating over elements
– Maintaining element order
– Storing key-value pairs
– Fast data retrieval based on keys
– Grouping related data

Read How to Create an Empty Tuple in Python?

Tips To Use {} and [] Effectively

Here are a few tips to keep in mind when working with {} and [] in Python:

  1. Choose the right data structure based on your needs. Use dictionaries ({}) when you need to store key-value pairs and lists ([]) when you need ordered collections.
  2. Be consistent with your naming conventions. Use descriptive names for your dictionaries and lists to enhance code readability.
  3. Leverage the built-in methods and functions provided by Python for working with dictionaries and lists. For example, use dict.get() to retrieve values from a dictionary safely, and use list.append() to add elements to a list efficiently.
  4. When iterating over a dictionary, you can use the items() method to access both keys and values simultaneously:
   for key, value in my_dict.items():
       print(f"Key: {key}, Value: {value}")
  1. If you need to check if a key exists in a dictionary, use the in operator:
   if "key" in my_dict:
       print("Key exists!")

By following these tips and understanding the differences between {} and [], you’ll be able to write cleaner, more efficient Python code.

Read How to Convert a Dictionary to an Array in Python?

Conclusion

In this tutorial, I explained the differences between using {} (curly braces) and [] (square brackets) in Python. I explained the basic difference between {} and [] in Python. We looked at real-world examples which shows how dictionaries can be used for storing user profiles and counting word frequencies, how lists can be employed for managing todo lists and processing data from CSV files, and comparison between lists and dictionaries in Python. I explained some tips to use {} and [] efficiently.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.