Get a Pentest and security assessment of your IT network.

Cyber Security

Python Dictionary Guide

TL;DR

This guide shows you how to create, add to, access and modify Python dictionaries. Dictionaries store information in key-value pairs – like a real-world dictionary where you look up a word (the key) to find its definition (the value).

Creating a Dictionary

  1. Empty Dictionary: Start with an empty dictionary using curly braces {}.
  2. Dictionary with Initial Values: Add key-value pairs directly within the braces, separated by commas. Keys and values are separated by colons.
my_dict = {} # Empty Dictionary
person = {"name": "Alice", "age": 30, "city": "London"} # With initial values

Adding to a Dictionary

  1. Using Square Brackets: Add new key-value pairs by assigning a value to a new key using square brackets.
  2. Updating Existing Values: Change the value associated with an existing key in the same way.
my_dict["name"] = "Bob"
my_dict["age"] = 25
person["city"] = "Manchester" # Update city

Accessing Dictionary Values

  1. Using Square Brackets: Retrieve a value by its key.
  2. get() Method: Use the get() method to retrieve values safely. If the key doesn’t exist, it returns None (or a default value you specify). This avoids errors.
name = person["name"] # Accessing name
age = my_dict.get("age") # Accessing age using get()
city = person.get("country", "Unknown") # Get country, default to 'Unknown' if not found

Modifying a Dictionary

  1. Changing Values: As shown earlier, use square brackets to change the value of an existing key.
  2. Deleting Key-Value Pairs: Use the del keyword followed by the dictionary name and the key in square brackets.
person["age"] = 31 # Change age
del person["city"] # Delete city

Dictionary Methods

  • keys(): Returns a view object containing all the keys in the dictionary.
  • values(): Returns a view object containing all the values in the dictionary.
  • items(): Returns a view object containing all key-value pairs as tuples.
  • pop(key): Removes and returns the value associated with the specified key. Raises an error if the key is not found.
keys = person.keys()
values = person.values()
items = person.items()
removed_age = person.pop("name") # Remove 'name' and get its value

Iterating Through a Dictionary

  1. Looping through Keys: Iterate directly over the dictionary to loop through its keys.
  2. Looping through Values: Use values() to iterate through the values.
  3. Looping through Key-Value Pairs: Use items() to iterate through both keys and values simultaneously.
for key in person:
    print(key, person[key]) # Loop through keys

for value in person.values():
    print(value) # Loop through values

for key, value in person.items():
    print(key, value) # Loop through key-value pairs

Checking if a Key Exists

  1. Using the in keyword: Check if a key exists in the dictionary using the in operator.
if "name" in person:
    print("Name exists!")
else:
    print("Name does not exist.")
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation