What is a Python Dictionary?
A dictionary in Python is a collection of key-value pairs. Think of it as a real-world dictionary, where you look up a word (key) to find its meaning (value). A dictionary allows you to store and retrieve data efficiently.
Key Features of a Python Dictionary:
- Unordered: The items do not have a specific order.
- Mutable: You can change the content (add, remove, update items).
- Indexed by keys: Instead of using numbers (like lists or arrays), you use keys.
Structure of a Dictionary
A dictionary is written using curly braces {}
, with each key-value pair separated by a colon (:
). Here’s the syntax:
my_dict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
1. Creating a Dictionary
Let’s start by creating a simple dictionary:
# Create a dictionary
person = {
"name": "John",
"age": 25,
"city": "New York"
}
print(person)
Output:
{'name': 'John', 'age': 25, 'city': 'New York'}
2. Accessing Values in a Dictionary
You can access values in a dictionary by referencing the key. For example, to get the name of the person:
print(person["name"]) # Output: John
Explanation: The code person["name"]
retrieves the value associated with the key "name"
, which is "John"
.
3. Adding Items to a Dictionary
You can add new key-value pairs to a dictionary like this:
# Add a new key-value pair
person["job"] = "Software Developer"
print(person)
Output:
{'name': 'John', 'age': 25, 'city': 'New York', 'job': 'Software Developer'}
4. Changing Values in a Dictionary
You can update the value of an existing key by referencing the key and assigning a new value:
# Change the value of an existing key
person["age"] = 26
print(person)
Output:
{'name': 'John', 'age': 26, 'city': 'New York', 'job': 'Software Developer'}
5. Removing Items from a Dictionary
You can remove items from a dictionary using the del
keyword or the pop()
method.
# Remove an item using del
del person["city"]
print(person)
Output:
{'name': 'John', 'age': 26, 'job': 'Software Developer'}
Alternatively, you can use pop()
:
# Remove an item using pop()
removed_value = person.pop("job")
print(person)
print("Removed Value:", removed_value)
Output:
{'name': 'John', 'age': 26}
Removed Value: Software Developer
6. Looping Through a Dictionary
You can loop through a dictionary to access each key and value. Here’s how:
# Loop through dictionary keys and values
for key, value in person.items():
print(key, ":", value)
Output:
name : John
age : 26
7. Checking If a Key Exists in a Dictionary
To check if a specific key is in the dictionary, you can use the in
keyword:
# Check if a key exists
if "name" in person:
print("The key 'name' is in the dictionary.")
Output:
The key 'name' is in the dictionary.
8. Dictionary Methods
Here are some useful methods you can use with dictionaries:
keys()
: Returns a list of keys in the dictionary.values()
: Returns a list of values in the dictionary.items()
: Returns a list of tuples, where each tuple is a key-value pair.
print(person.keys()) # Output: dict_keys(['name', 'age'])
print(person.values()) # Output: dict_values(['John', 26])
print(person.items()) # Output: dict_items([('name', 'John'), ('age', 26)])
Displaying Code and Output on WordPress
To display Python code and its output on a WordPress page or post, you can follow these steps:
Step 1: Install a Code Syntax Highlighter Plugin
First, install a plugin like “SyntaxHighlighter Evolved” or “Crayon Syntax Highlighter” to format and display your code in a readable manner.
Step 2: Embed Python Code in WordPress
Once the plugin is installed, you can embed your Python code in a post or page like this:
[code language="python"]
# Create a dictionary
person = {
"name": "John",
"age": 25,
"city": "New York"
}
# Print the dictionary
print(person)
[/code]
Step 3: Add Sample Output
You can add the sample output below the code block in the post like this:
<p><strong>Output:</strong></p>
<pre>
{'name': 'John', 'age': 25, 'city': 'New York'}
</pre>