How to Convert a String to a Dictionary in Python

Python string to dictionary: Command Prompt output of ast.literal_eval turning a dict string into a dict

To convert a string to a dictionary in Python, use ast.literal_eval() when the text looks like a Python dict (single quotes, True, None), and json.loads() when it’s JSON. Both return a real dict: I tested these conversions on Python 3.12.5 from Command Prompt, feeding them made-up US customer orders. The right tool depends on what … Read more >>

How to Update Values in a Python Dictionary

Update values in a Python dictionary: Command Prompt output of new prices after assignment

Assign to the key. That’s the whole trick to update values in a Python dictionary: d[key] = new_value replaces the old value, and d.update() changes several keys in one call: A small coffee-shop price list runs through every example, and each output was captured on Python 3.12.5. In this tutorial, we’ll change one value, several … Read more >>

Create an Empty Dictionary in Python ({} vs dict())

Create an empty dictionary in Python: the Command Prompt showing dict.fromkeys giving every key the same list object

Creating an empty dictionary in Python takes one pair of braces: Both give you a real dictionary with no keys in it. The braces are the common choice, and they are marginally faster, but the two are interchangeable. What follows covers filling it afterwards, starting one with keys already in place, and the three ways … Read more >>

How to Check if a Tuple is Empty in Python

empty tuple in python

I’ve often found myself handling large datasets where data consistency is a constant battle. Whether I’m pulling sales tax data from a US Treasury API or processing New York Stock Exchange (NYSE) ticker symbols, I frequently encounter empty tuples. An empty tuple can break your logic if you try to access its elements, so knowing … Read more >>

How to Calculate the Dot Product in Python Without NumPy

dot product python without numpy

I often find myself working on lightweight Python scripts where I want to avoid the overhead of heavy libraries like NumPy. Whether you are working on a restricted server or just want to understand the underlying math, calculating a dot product manually is a great exercise. In my years of developing Python applications, I’ve realized … Read more >>

KeyError in Python: How to Fix a Dictionary KeyError

Python dictionary KeyError: Command Prompt traceback ending in KeyError: 'mango' while totaling an order

Your script was adding up an order, then it stopped dead with KeyError: ‘mango’. That’s Python saying the dictionary has no such key. The right fix depends on whether that key should exist. Quick answer: a Python dictionary KeyError happens when d[key] asks for a key that isn’t there. Check it first with key in … Read more >>

Tic Tac Toe Game in Python (With Unbeatable AI)

Tic tac toe game in Python: Command Prompt output of the board and winner check

A tic tac toe game in Python needs three pieces: a list of nine squares for the board, a function that checks the eight winning lines, and a loop that asks each player for a move. The winner check is the heart of it: I really played the game below in Command Prompt on Python … Read more >>

How to Print a Stack Trace in Python (traceback Module)

Print stack trace in Python: Command Prompt output of traceback.print_exc inside an except block

The simplest way to print a stack trace in Python without crashing is traceback.print_exc() inside an except block. It prints the full traceback, exactly as an uncaught error would, and your program keeps running: Each traceback below is real output from Python 3.12.5, captured in Windows Command Prompt. I’ll show print_exc(), getting the trace as … Read more >>

TypeScript Type Casting: as, Angle Brackets and Safe Casts

TypeScript type casting: VS Code showing JSON.parse cast to an Order interface with the as keyword and its output

If you’ve tried to write input as number on a string, you’ve probably seen error TS2352 and wondered why TypeScript type casting refuses. The fix: use as to describe data, and Number() to change it. That’s because a TypeScript cast is only a note to the compiler. It never touches the value at runtime, so … Read more >>

How to Initialize a Map in TypeScript (With Examples)

Initialize a Map in TypeScript: VS Code showing a typed Map built from an array of key-value pairs and its output

To initialize a Map in TypeScript with data, pass an array of [key, value] pairs to the constructor and put the types in angle brackets: That gives a typed Map<string, number>, and TypeScript rejects later set() calls with the wrong types. In this tutorial, I’ll show you how to initialize a Map in TypeScript five … Read more >>