When to use List vs Dict in Python?

ยท

2 min read

Lists

  • Only a single data point for each item
  • To find an item we have to loop the whole list
my_books = ["Atomic Habits", "Life is what you make it", "power of habits"]

Dictionaries

Used to store Multiple attributes for a single item

my_books = {
            "book_name": "Life is what you make it ",
            "author": "Preethi Shenoy",
            "pages": 150,
           }

List of Lists

my_books = [
    ["Atomic Habits", "James Clear", 200],
    ["Life is what you make it", "Preethi Shennoy", 150],
    ["power of habits", "", 320],
]
  • Can store multiple attributes and multiple items
  • But Searching still is difficult. We have to often loop n x n times
  • The attributes don't have key properties, therefore readability isn't great my_books[1][2]

List of Dicts

book_as_dict = [
    {"book_name": "Atomic Habits", "author": "James Clear", "pages": 200},
    {
        "book_name": "Life is what you make it ",
        "author": "Preethi Shenoy",
        "pages": 150,
    },
    {"book_name": "LoonShots", "author": "", "pages": 200},
  • Can store multiple attributes and multiple items
  • Searching is O(n)
  • Better readability than list of lists my_books[1]["book_name"]

Dict of Dicts

  • Can find item at O(1) only on data point(the dict key)
  • Can store multiple attributes and multiple items
book_as_dict = {
    "Atomic Habits": {
        "book_name": "Atomic Habits",
        "author": "James Clear",
        "pages": 200,
    },
    "Life is what you make it ": {
        "book_name": "Life is what you make it ",
        "author": "Preethi Shenoy",
        "pages": 150,
    },
    "LoonShots": {"book_name": "LoonShots", "author": "", "pages": 200},
}
ย