Read A CSV File To List Of Dictionaries In Python

The most common form of data I have played with is generally found in CSV format. This makes the data easy to understand but difficult to modify or change, especially when the CSV file contains lots of columns. In this article I will demonstrate how I frequently use this file format to import it into a useable data structure in Python, namely, a list of Python dictionaries. Let’s start with defining the basic terminology so we’re on the same page before jumping into some examples. ...

January 20, 2024 · 21 min · 4348 words · Ryan Sheehy

Python List Not Appending? Troubleshooting - Solutions for Beginners

Why does a Python list not append an item? When you use the list method .append() to insert a list item to the end of its existing contents, you could be in for a surprise if this doesn’t happen in some instances. The main reasons for why this may occur are due to the improper usage of the list method or adding a variable that doesn’t actually contain the information expected. ...

October 10, 2023 · 9 min · 1807 words · Ryan Sheehy

2 Ways To Create A Python List With Identical Elements: One-Liners

How can you create a list with identical elements in it with Python? There are two ways to create a list with identical elements in Python. One method is fairly straightforward and easy to remember, whereas the other involves the itertools library. The one I apply the most in my Python coding is the method that uses the asterisk operator to a list containing the item I want to replicate. The other method uses the resources and techniques of a library with a function that is difficult to forget: itertools.repeat() ...

June 11, 2023 · 5 min · 913 words · Ryan Sheehy

Fix NameError: Python List Is Undefined

How do you fix the NameError: Python list is undefined type errors? When you get this error in your Python code there are a few ways to fix the problem and in essence, the easy fix is to check you’re working on a list variable that has been initiated as a list. The three common causes I have found in my own Python code for why this error pops up is due to: 1. not instantiating a variable as a list; 2. incorrectly typing the name of the list variable; or 3. using a variable in a list that hasn’t been declared. ...

June 11, 2023 · 5 min · 929 words · Ryan Sheehy

Python List Not Sorting: Troubleshooting With Examples

Why does a list not sort properly in Python as expected? There are a couple of reasons why a list may not have sorted as expected in Python. Here are a couple of ways to diagnose the problem to help you check. Here’s a quick list (no pun intended!) you can use to quickly check: Are all elements within the list of the same data type? Look at setting them to the same data type using the key parameter Are you capturing the result of a .sort() method? Change this sort operation to the sorted() function Are you sorting items with mixed case? Apply the key parameter converting all items to .lower() Do you understand the key parameter? Extract the lambda function to check it works on elements in your list. Are you sorting in reverse? Check the reverse parameter to your sort function. False is the default setting it this parameter is not defined. Are you sorting unicode characters? Look to use a standard encoding type with the key parameter using lambda x : x.encode('utf-8'). Are there any whitespace characters wrapping the elements? Apply the .strip() string method to each element with the key parameter. Let’s explore each of these items in a little more detail with examples. Here are some reasons why your Python lists may not be sorting properly: ...

June 10, 2023 · 7 min · 1289 words · Ryan Sheehy

Python Lists: Order Alphabetically & Sorting Examples

How do you sort a Python list alphabetically? There are two easy ways to sort a list in Python: using the standard sorted() function or using the .sort() list method. Assuming you have a list of strings you can apply either method to sort the list alphabetically. If you have a list of numbers and strings you can use the parameter key to change all values within the list to a str data type and then perform the necessary sort (more on that later). ...

June 10, 2023 · 9 min · 1854 words · Ryan Sheehy

Copy List Using [:] In Python

The empty slice operator [:] in Python is a powerful and concise way of copying a list. It is shorthand syntax allowing you to create a new list that contains all the elements of the existing list where the operator is used. This operator is represented by one colon wrapped in square brackets [:] with no values or spaces inside. While the empty slice operator may seem like a simple and straightforward way to copy a list, it is important to note that it only creates a shallow copy. This means that if the list contains mutable objects, such as other lists or dictionaries, the new list will still reference the objects contained in the original list. Therefore, any changes made to the original objects will also be reflected in the new copied list. ...

March 25, 2023 · 4 min · 706 words · Ryan Sheehy

Why Does list1 = list2 Not Create A Copy In Python

When starting out in Python it can be easy to think that the expression list2 = list1 will make list2 contain a copy of list1. But it doesn’t take long to realise that this doesn’t meet expectations of what actually happens in the wild. Take the following code as an example: 1 2 3 4 5 6 7 >>> list1 = [1, 2, 3, 4, 5] >>> list2 = list1 >>> list1.append(6) >>> print(list1) [1, 2, 3, 4, 5, 6] >>> print(list2) [1, 2, 3, 4, 5, 6] Huh? Why did list2 contain the same contents as list1 even when the insertion of additional elements in list1 happened after list2 had already been assigned? ...

March 24, 2023 · 9 min · 1715 words · Ryan Sheehy

Sort List By Second (or Nth) Element In Python: 1 Line Of Code

How do you sort a list of lists by the second element using Python? To sort a list of lists by the second element in each list use the key parameter to either the .sort() list function (if modifying the original list) or the sorted() function (if returning a new list). Here’s an example demonstrating how you can do this with code: 1 2 3 4 >>> list_2d = [['2nd', 2], ['3rd', 3], ['1st', 1]] >>> list_2d.sort(key=lambda x: x[1]) >>> print(list_2d) [['1st', 1], ['2nd', 2], ['3rd', 3]] As you can see from the above code the key parameter in the .sort() list function uses a lambda expression which takes each list and extracts the second element. This is used as the key to determine how each list will be sorted. ...

November 5, 2022 · 2 min · 320 words · Ryan Sheehy

Python: Sort List Of Tuples By First Element In 10 Seconds

How do you sort a list of tuples by the first element in each tuple in Python? To sort a list of tuples in Python use the .sort() list method if you want to modify the list to sort or the sorted() function if you want to generate a new list. Use the parameter key with either function and set the value of that parameter to a lambda expression that returns the required tuple you want to sort by. ...

June 16, 2022 · 2 min · 418 words · Ryan Sheehy