Python | Accessing Key-value in Dictionary

Python | Accessing Key-value in Dictionary

In Python, a dictionary is a collection of key-value pairs. Accessing the keys and their corresponding values is a fundamental operation when working with dictionaries.

Objective: Learn to access and manipulate keys and values in a Python dictionary.

1. Accessing a value using a key:

To access the value for a particular key, you use square brackets [].

data = {"name": "John", "age": 30} print(data["name"]) # Outputs: John 

However, directly using this method can lead to a KeyError if the key doesn't exist in the dictionary. To handle this gracefully, you can use the get() method:

print(data.get("name")) # Outputs: John print(data.get("address")) # Outputs: None print(data.get("address", "Address not found!")) # Outputs: Address not found! 

2. Iterating through keys and values:

You can use the dictionary methods keys(), values(), and items() to retrieve keys, values, or both, respectively.

# Iterating through keys for key in data.keys(): print(key) # Iterating through values for value in data.values(): print(value) # Iterating through both keys and values for key, value in data.items(): print(f"{key}: {value}") 

3. Checking if a key exists:

You can use the in keyword to check if a key is present in the dictionary:

if "name" in data: print("Name exists in the dictionary!") 

4. Modifying values:

To modify a value for a specific key, use the assignment operation:

data["name"] = "Doe" print(data) # Outputs: {'name': 'Doe', 'age': 30} 

5. Adding new key-value pairs:

Simply assign a value to a new key:

data["address"] = "123 Main St" print(data) # Outputs: {'name': 'Doe', 'age': 30, 'address': '123 Main St'} 

Summary:

Dictionaries in Python are mutable, unordered collections of key-value pairs where keys are unique. You can access, modify, add, and delete key-value pairs, making dictionaries an extremely versatile data structure in Python.


More Tags

angular2-forms string-length android-spinner npm-install chai touchablehighlight image-segmentation datetimeoffset angular text-to-speech

More Programming Guides

Other Guides

More Programming Examples