📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Python Dictionary Operations with Outputs

Common dictionary operations in Python, organized by topic, with example outputs.

Creating and Accessing Dictionaries

# Creating a dictionary
my_dict = {"apple": 1, "banana": 2, "orange": 3}
print(my_dict)
# Output: {'apple': 1, 'banana': 2, 'orange': 3}

# Accessing values
print(my_dict["apple"])
# Output: 1

# Using get() method (safer if key might not exist)
print(my_dict.get("grape", 0))
# Output: 0 (default value)

Modifying Dictionaries

# Adding or updating key-value pairs
my_dict["grape"] = 4
my_dict["apple"] = 5
print(my_dict)
# Output: {'apple': 5, 'banana': 2, 'orange': 3, 'grape': 4}

# Removing items
del my_dict["banana"]
popped_value = my_dict.pop("orange")
print(f"Popped value: {popped_value}")
# Output: Popped value: 3
print(my_dict)
# Output: {'apple': 5, 'grape': 4}

# Clear all items
my_dict.clear()
print(my_dict)
# Output: {}

Checking and Iterating

my_dict = {"apple": 5, "orange": 3, "grape": 4}

# Checking if a key exists
if "apple" in my_dict:
    print("Apple is in the dictionary")
# Output: Apple is in the dictionary

# Getting all keys, values, and items
print(f"Keys: {list(my_dict.keys())}")
# Output: Keys: ['apple', 'orange', 'grape']
print(f"Values: {list(my_dict.values())}")
# Output: Values: [5, 3, 4]
print(f"Items: {list(my_dict.items())}")
# Output: Items: [('apple', 5), ('orange', 3), ('grape', 4)]

# Iterating over a dictionary
for key, value in my_dict.items():
    print(f"{key}: {value}")
# Output:
# apple: 5
# orange: 3
# grape: 4

Dictionary Comprehension and Merging

# Dictionary comprehension
squared_dict = {x: x**2 for x in range(5)}
print(squared_dict)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Merging dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
# Output: {'a': 1, 'b': 3, 'c': 4}

# Or use the update method
dict1.update(dict2)
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}

Copying Dictionaries

original = {"a": 1, "b": {"c": 2}}
shallow_copy = original.copy()
import copy
deep_copy = copy.deepcopy(original)

original["b"]["c"] = 3
print(f"Original: {original}")
# Output: Original: {'a': 1, 'b': {'c': 3}}
print(f"Shallow copy: {shallow_copy}")
# Output: Shallow copy: {'a': 1, 'b': {'c': 3}}
print(f"Deep copy: {deep_copy}")
# Output: Deep copy: {'a': 1, 'b': {'c': 2}}

Advanced Dictionary Usage

# Default dictionaries
from collections import defaultdict
default_dict = defaultdict(int)
default_dict["new_key"] += 1
print(default_dict)
# Output: defaultdict(<class 'int'>, {'new_key': 1})

# Accessing nested dictionaries
nested_dict = {"outer": {"inner": "value"}}
print(nested_dict["outer"]["inner"])
# Output: value

# Dictionary unpacking in function calls
def print_info(name, age):
    print(f"{name} is {age} years old")

person = {"name": "Alice", "age": 30}
print_info(**person)
# Output: Alice is 30 years old