You are currently viewing Dictionaries and dictionary manipulation in python Data Structures

Dictionaries and dictionary manipulation in python Data Structures

Dictionaries are a type of data structure in Python that store key-value pairs. They are also sometimes called “hash tables” or “associative arrays” in other programming languages.

To create a dictionary in Python, you can use curly braces to enclose a comma-separated sequence of key-value pairs, where each key-value pair is separated by a colon:

phonebook = {'Alice': '123-456-7890', 'Bob': '987-654-3210', 'Charlie': '555-123-4567'}
You can also use the dict() constructor to create a dictionary from a sequence of key-value pairs:
phonebook = dict([('Alice', '123-456-7890'), ('Bob', '987-654-3210'), ('Charlie', '555-123-4567')])
You can access the value associated with a particular key in a dictionary using indexing, just like with lists:
print(phonebook['Bob'])  # '987-654-3210'
If you try to access a key that doesn’t exist in the dictionary, you will get a KeyError:
print(phonebook['Eve'])  # KeyError: 'Eve'

To avoid this error, you can use the get() method instead, which will return None (or a default value that you specify) if the key doesn’t exist:

print(phonebook.get('Eve'))  # None
print(phonebook.get('Eve', 'Not found'))  # 'Not found'
You can add new key-value pairs to a dictionary by simply assigning a value to a new key:
phonebook['Eve'] = '555-555-5555'
You can also modify existing values by assigning a new value to an existing key:
phonebook['Charlie'] = '555-987-6543'
You can use the del keyword to remove a key-value pair from a dictionary:
del phonebook['Bob']

You can use the keys() method to get a list of all the keys in a dictionary, and the values() method to get a list of all the values:

print(list(phonebook.keys()))  # ['Alice', 'Charlie', 'Eve']
print(list(phonebook.values()))  # ['123-456-7890', '555-987-6543', '555-555-5555']

Finally, you can use the len() function to get the number of key-value pairs in a dictionary:

print(len(phonebook))  # 3

Dictionaries are another built-in data structure in Python that allows you to store a collection of key-value pairs. They are similar to lists and tuples, but instead of using numeric indices to access elements, they use keys that can be of any immutable type, such as strings or numbers.

Here’s an example of how to define a dictionary in Python:
# Define a dictionary
person = {
    "name": "John",
    "age": 30,
    "gender": "Male"

In this example, the dictionary person contains three key-value pairs. The keys are “name”, “age”, and “gender”, and the values are “John”, 30, and “Male”, respectively.

You can access the values of a dictionary by using the keys, like this:

# Accessing values
print(person["name"])    # Output: John
print(person["age"])     # Output: 30
print(person["gender"])  # Output: Male
To add a new key-value pair to a dictionary, you can simply assign a value to a new key, like this:
# Adding a new key-value pair
person["occupation"] = "Engineer"
print(person)  # Output: {'name': 'John', 'age': 30, 'gender': 'Male', 'occupation': 'Engineer'}
To modify an existing value in a dictionary, you can simply assign a new value to the corresponding key, like this:
# Modifying an existing value
person["age"] = 35
print(person)  # Output: {'name': 'John', 'age': 35, 'gender': 'Male', 'occupation': 'Engineer'}
To remove a key-value pair from a dictionary, you can use the del keyword, like this:
# Removing a key-value pair
del person["gender"]
print(person)  # Output: {'name': 'John', 'age': 35, 'occupation': 'Engineer'}

You can also use various dictionary methods to manipulate dictionaries, such as keys(), values(), items(), get(), pop(), clear(), and others. These methods allow you to access the keys, values, and items (key-value pairs) of a dictionary, get the value of a key (with a default value if the key does not exist), remove a key-value pair from a dictionary and return its value, and clear all key-value pairs from a dictionary, respectively.

# Using dictionary methods
print(person.keys())    # Output: dict_keys(['name', 'age', 'occupation'])
print(person.values())  # Output: dict_values(['John', 35, 'Engineer'])
print(person.items())   # Output: dict_items([('name', 'John'), ('age', 35), ('occupation', 'Engineer')])
print(person.get("gender", "Unknown"))  # Output: Unknown
print(person.pop("occupation"))         # Output: Engineer
print(person)  # Output: {'name': 'John', 'age': 35}
print(person)  # Output: {}
I hope this helps!

Leave a Reply