Ticker

6/recent/ticker-posts

Dictionary in Python

Dictionary in Python

Introduction
A dictionary is a built-in data type in Python that stores key-value pairs. It is also known as an associative array or hash table in other programming languages. Dictionaries are mutable, unordered, and allow for fast access to values using keys.

Creating a Dictionary
To create a dictionary in Python, you can use curly braces {} or the dict() constructor. Each key-value pair is separated by a colon :.

python
# Using curly braces
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Using dict() constructor
another_dict = dict(name='Alice', age=25, city='London')

Accessing Values
You can access values in a dictionary using their corresponding keys.

python
print(my_dict['name']) # Output: John
print(another_dict['age']) # Output: 25

Adding and Modifying Items
To add a new key-value pair or modify an existing one, simply assign the value to the desired key.

python
my_dict['occupation'] = 'Engineer' # Adding a new key-value pair
another_dict['age'] = 26 # Modifying an existing value

Dictionary Methods
Python provides several methods to manipulate dictionaries. Some common ones include:

  • get(): Retrieves the value for a given key, returns a default value if the key is not found.
  • keys(): Returns a view of all the keys in the dictionary.
  • values(): Returns a view of all the values in the dictionary.
  • items(): Returns a view of all key-value pairs as tuples.
python
print(my_dict.get('name', 'Unknown')) # Output: John
print(another_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

Removing Items
You can use the del keyword to remove a specific key-value pair from the dictionary.

python
del my_dict['city'] # Removes the key 'city' and its corresponding value from my_dict

Checking Key Existence
You can use the in keyword to check if a key exists in the dictionary.

python
if 'name' in my_dict:
print("Name exists.")
else:
print("Name not found.")

Looping Through a Dictionary
You can loop through a dictionary's keys, values, or items using loops.

python
for key in my_dict:
print(key, my_dict[key])

for value in my_dict.values():
print(value)

for key, value in my_dict.items():
print(key, value)

Conclusion
Dictionaries are powerful data structures in Python that allow you to store and access data efficiently using key-value pairs. They are widely used in various applications, from storing configuration settings to handling complex data mappings. Understanding dictionaries is essential for every Python programmer.

Post a Comment

0 Comments