Python Dictionaries with examples


Python dictionaries are dynamic collections that store data in key-value pairs, allowing for rapid access to values based on their associated keys. These structures offer a potent amalgamation of simplicity and efficiency, making them a go-to choice for managing various data types.

 

The Anatomy of Dictionaries

 

A Python dictionary consists of two vital components:

Keys

Keys serve as the linchpins that facilitate the indexing of values within dictionaries. They are unique and immutable, often comprising strings, numbers, or even tuples.

Values

Values, on the other hand, can be of any data type, ranging from integers and strings to more complex objects. They are associated with their corresponding keys and can be modified or accessed effortlessly

 

Creating Dictionaries

 

Designing dictionaries in Python is a breeze. Utilize a pair of curly braces to initiate a dictionary, with key-value pairs separated by colons. For instance:

student_grades = {

    "Alice": 95,

    "Bob": 87,

    "Eve": 92
}

 

Accessing and Modifying Dictionary Entries 

 

Accessing values in a dictionary is straightforward. Use the key inside square brackets to retrieve the associated value. If the key is not present, Python raises a KeyError. To avoid this, you can use the get() method. Modifying values is as simple as reassigning a new value to an existing key.

 

Accessing Dictionary Entries
my_dict = {

    'name': 'John',

    'age': 30,

    'city': 'New York'

}

# Using square brackets to access values

name = my_dict['name']

age = my_dict['age']

# Using get() method to access values (handles missing keys gracefully)

city = my_dict.get('city', 'Default City')  # Provides a default value if 'city' is missing

print(name)

print(age)

print(city)

Output

John 30 New York

 

Modifying Dictionary Entries
my_dict = {

    'name': 'John',

    'age': 30,

    'city': 'New York'

}

# Modifying values

my_dict['age'] = 31

my_dict['city'] = 'San Francisco'

print(my_dict)


Output

{ 
  'name': 'John',

  'age': 31, # age is updated to 31 '

  city': 'San Francisco' # city is updated to 'San Francisco' 
}

 

Remember that if you try to access a key that doesn't exist using square brackets (my_dict['nonexistent_key']), it will raise a KeyError. On the other hand, using the get() method allows you to provide a default value when the key is not found.

 

Retrieving Elements From a Dictionary

You can retrieve elements from a dictionary by using their keys. Here's a bit more detail and an example:

my_dict = {

    'name': 'John',

    'age': 30,

    'city': 'New York'

}



# Using keys to retrieve values

name = my_dict['name']

age = my_dict['age']



# Using get() method with a default value

city = my_dict.get('city', 'Default City')



print(name)

print(age)

print(city)

Output

name = 'John'
age = 30
city = 'New York'

 

Updating a Dictionary

You can update or add elements to a dictionary by assigning new values to existing keys or by adding new key-value pairs. Here's how:

my_dict = {

    'name': 'John',

    'age': 30,

    'city': 'New York'

}

# Updating values

my_dict['age'] = 31

my_dict['city'] = 'San Francisco'

# Adding a new key-value pair

my_dict['occupation'] = 'Engineer'

print(my_dict)

Output

{
    'name': 'John',
    'age': 31,            # age is updated to 31
    'city': 'San Francisco',  # city is updated to 'San Francisco'
    'occupation': 'Engineer'  # a new key 'occupation' is added with the value 'Engineer'
}

 

Nested Dictionaries

 

Dictionaries can also be nested within one another, creating complex data structures. This is useful when dealing with hierarchical or structured data. For example

# Nested dictionary

employee = {

    'personal_info': {

        'name': 'Alice',

        'age': 30

    },

    'job_info': {

        'title': 'Software Engineer',

        'experience': '5 years'

    }

}

Output

{

    'personal_info': {

        'name': 'Alice',

        'age': 30

    },

    'job_info': {

        'title': 'Software Engineer',

        'experience': '5 years'

    }

}

 

Different Data Types a Dictionary Can Hold

 

Python dictionaries are quite versatile when it comes to the types of data they can hold. Dictionaries can store a wide range of data types as both keys and values. Here's a list of some common data types that dictionaries can hold:

 

Numeric Types

Integers: int

Floating-Point Numbers: float

Text Types

Strings: str

Boolean Type

Booleans: bool (True or False)

Sequence Types

Lists: list

Tuples: tuple

Mapping Types

Nested Dictionaries: You can have dictionaries within a dictionary, creating a hierarchical structure.

Custom Objects

You can use custom objects as dictionary values, where the keys act as identifiers for the objects.

Functions

You can use functions as dictionary values, associating keys with callable functions.

Modules and Classes

Modules and classes can be used as dictionary values, allowing you to associate keys with specific functionalities or behaviors.

Mixed Data Types

Dictionaries can hold a mix of different data types as both keys and values. For example, a dictionary could have integers as keys and lists or strings as values

 

Here is an example of a dictionary holding different Data Types:

my_dict = {

    'name': 'Alice',

    'age': 25,

    'is_student': True,

    'grades': [85, 90, 78],

    'address': {

        'street': '123 Main St',

        'city': 'Anytown',

        'zip': '12345'

    }

}

print(my_dict['name'])

print(my_dict['age'])

print(my_dict['is_student'])

print(my_dict['grades'])

print(my_dict['address'])

Output

Alice

25

True

[85, 90, 78]

{'street': '123 Main St', 'city': 'Anytown', 'zip': '12345'}

 

Dictionary Methods

 

Python dictionaries come with a variety of methods that facilitate common operations:

keys(): Returns a list of all keys in the dictionary.

values(): Returns a list of all values in the dictionary.

items(): Returns a list of key-value pairs as tuples.

get(key, default): Retrieves the value for a key, or a default value if the key doesn't exist.

update(dict2): Updates the dictionary with key-value pairs from another dictionary.

pop(key): Removes and returns the value associated with a key

 

Versatility in Applications

 

Python dictionaries find their utility across a myriad of applications:

1. Data Aggregation

Dictionaries excel at aggregating data from various sources. This proves invaluable in scenarios such as analyzing user preferences or summarizing sales data.

 

2. Configuration Settings

They serve as an elegant choice for storing configuration settings in applications, providing a structured approach to managing various parameters.

 

3. Language Translation

Dictionaries can facilitate language translation by mapping words or phrases from one language to another.

 

Summary

 

Python dictionaries are indispensable tools for managing data efficiently within your programs. Their capacity to swiftly retrieve information, coupled with their versatility, makes them an essential asset for programmers of all levels. Incorporate dictionaries into your coding arsenal and unlock a new realm of streamlined data manipulation.



Thanks for feedback.



Read More....
Arrays and Lists in Python
Python Iterators
Lambda or Anonymous Functions in Python
Most common built-in methods in Python
Python Decorators