Tag

dictionaries

7 guides filed under this subject.

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…

Read guide

Python Initialize Dictionary: Use Dict Constructor Or Dict Literal?

How do you initialize an empty dictionary in Python? Is it best to use dict() or {} ? There are two common ways of initializing a dictionary in Python. One involves using the built-in function dict() and is known as the dict constructor , whereas the other method is known as dict literal and has the syntax {} . Here’s an example demonstrating how to initialize using both approaches in…

Read guide

Sort Dict By Value Or Sort Dict By Key In Python: 1 Liners

It can be easy to sort a list, whether a list of strings or even a list of dictionaries, but can you sort a dictionary? One way to sort a dictionary by the values of each key : value pair in Python is to use a dictionary comprehension . Dictionary comprehensions are very similar to list comprehensions and have the following schema: The first expression within the dictionary comprehension, the…

Read guide

Enumerate Dictionary In Python: Video Demonstration

Previously I looked at how to use the enumerate() built-in function with a for loop to provide two variables when iterating through a list. In that article the enumerate() function provides both an index number and the element in each list by wrapping these together into a tuple. But what happens when the enumerate() function is applied to a dictionary? As done previously let’s inspect the output of the enumerated…

Read guide

Create A Dictionary In Python: Quick 5 Minute Beginners Guide

How do you create a dictionary in Python? Dictionaries in Python are mutable data types that contain key: value pairs. A dictionary can be a great way to organise information, especially if checks need to be performed prior for uniqueness and/or the value of that key needs to be changed, skipped or inserted. Creating A Dictionary Dictionaries can be created using either the dict() constructor method, using the dict literal…

Read guide

Sort Nested Dictionary By Key Or By Value In Python: One Liner

How do you sort a nested dictionary in Python by key or by value? Throughout this article, I will use the following example, which displays a nested dictionary that contains three main properties labelled dict1 , dict2 , dict3 and from each key they reference another dictionary which contains a simple dictionary of three keys labelled A , B and C with each key matched to the same value 1…

Read guide