Thursday, February 29, 2024

DICTIONARIES IN PYTHON

Python Dictionaries

Introduction

  • Definition and Structure
  • Key Characteristics
  • Accessing Values
  • Dictionary Methods
  • Adding and Modifying Entries
  • Removing Entries
  • Dictionary Comprehensions
  • Iterating Over Dictionaries
  • Nested Dictionaries
  • Dictionary Operations and Comparisons

Python dictionaries and their uses will be covered in this section. Dictionary data is diverse and easy to arrange and retrieve. They help link relevant data for better data management. This chapter covers creating, accessing, and modifying dictionaries. Dictionaries are more flexible than lists because their keys can be any data type. With dictionaries, information storage is nearly infinite.

Python calls dictionaries “dict”; other languages call them “hashes”. In a dictionary, indexes are called “keys” and always have a value, therefore they are called key-value pairs. Braces {} are used to type dictionaries. In this chapter, we will look at various Python dictionary examples and learn about dictionaries in Python.

Dictionary

Python dictionaries and their uses will be covered in this section. Dictionary in Python is data that is diverse and easy to arrange and retrieve. They help link relevant data for better data management. This chapter covers creating, accessing, and modifying dictionaries. Dictionaries are more flexible than lists because their keys can be any data type. With dictionaries, information storage is nearly infinite.

Python calls dictionaries “dict”; other languages call them “hashes”. In a dictionary, indexes are called “keys” and always have a value, therefore they are called key-value pairs. Braces { } are used to type dictionaries. below is the basic code for a dictionary in Python or how we create a dict in Python.

In the above code we can see that we created a dictionary the “hinting” using the dict() function and we can verify that it creates a dictionary because when we print it, it prints the empty braces {} which represent the dictionary.

Now let’s look at that type of dictionary which we mainly create in Python programming for our problem-solving. 

The Python code above creates a dictionary named “mydog” with a key-value pair. We also see that the keys are strings, which we've covered, and may be any type.

Python dictionaries fetch values for keys. A colon links each dictionary key to its value, while commas divide key-value pairs. Dictionaries may store any number of key-value pairs, making data organization and access flexible.

Real-World Example of Python Dictionary Usage

To better understand the Python Dictionary let’s take an example suppose we are building a student management system for a school using Python dictionaries to store and manage student information. Each student has unique attributes such as name, age, grade, and subjects enrolled. Here’s how we can use Python dictionaries for this purpose:

# Dictionary to store student information

students = {

    "101": {"name": "Alice", "age": 15, "grade": 10, "subjects": ["Math", "Science", "English"]},

    "102": {"name": "Bob", "age": 14, "grade": 9, "subjects": ["History", "Geography", "Math"]},

    # Additional students can be added similarly

}

With this dictionary structure, we can easily access and manipulate student information. For instance, to add a new student we just need to write the below code:

new_student = {"name": "Charlie", "age": 16, "grade": 11, "subjects": ["Physics", "Chemistry", "Biology"]}

students["103"] = new_student

To update the subjects for a specific student, let’s say Bob we just need to write the following code:

students["102"]["subjects"].append("Computer Science")

To display the subjects enrolled by a particular student, such as Alice we need to write the below code:

alice_subjects = students["101"]["subjects"]

print("Subjects enrolled by Alice:", alice_subjects)

Furthermore, we can iterate over the dictionary to perform operations on all students, such as calculating the average age or printing the names of students in a particular grade.

In conclusion, Python dictionaries provide an efficient way to organize and manage student information in a student management system, allowing easy access, update, and retrieval of student data.

Simple Dictionary

Let's examine a basic dictionary. A basic dictionary holds item-specific information. Consider a dictionary named alien with multiple colors and point values. Let's look at Python code to understand.

In the above code, we can see that alien1 stores the alien’s color and point values, and we can access them using square brackets and passing a key inside them.

Accessing Values in a Dictionary

As seen above, we use the dictionary's name and the key in square brackets to obtain an item or value. This tells Python to return the key value means we are accessing values in the dictionary Python.

If we made a game with aliens and earned points by shooting them, we could indicate how many points the player should earn using the code below.

The preceding code stores key “points” values from the dictionary in the new_points variable. After that, we transform the integer value to a string and utilize it to build a statement about the player's points, which is reported to the console. 

Adding New Key-Value Pairs

Python dictionaries are dynamic, so we can quickly add new key-value pairs. Steps to add a new entry: Open square brackets and enter the new key name after specifying the dictionary name. We use the assignment operator to link the key and its value after closing the square brackets. Once this is done, printing the dictionary again will show the updated key-value pair. Coding will demonstrate this technique.

The following code snippet prints the dictionary after it has been formed with two keys and values on the first line, updated with new keys and values on the second line, and finally printed.

Dictionaries vs. Lists

Item order is store-like in the list but not in the dictionary. We use a square bracket with list_name to access the first item, which is list_name[0], but the dictionary has no first value or index. The order of elements in a list determines whether two lists are the same, whereas, with dictionaries, it doesn't matter what key-value pairs are written. For clarity, let's examine Python code for both.

In the above code, we can see that list1 and list2 have the same items but they are in different orders, and when we compare them using the equal to operator, they print False. on the other hand, dict1 and dict2 have the same key-value pairs in different order, but when we compare them using the equal to operator, the dictionary prints "true," which shows that both dictionaries are equal. If sorted, dictionaries might be lists, but they're not.

If we access a key not in the dictionary, we receive a KeyError, which is similar to the list's “out-of-range” IndexError. Python code that accesses a key not in the dictionary shows the error.

The Python interpreter displays the anticipated KeyError error in the above code.

Python dictionaries may take any key-value pair, enabling sophisticated data organization. Consider creating a birthday management program for pals. We can conveniently store their information in a dictionary using each friend's name as a key and their birthdate as a value. Simply enter the new friend's name and birthdate to update the dictionary. Let's code this application in Python. 

The code snippet creates a dictionary called "birthdays" with names as keys and birthdays as values. The program searches the dictionary for user-entered names. If the birthdate is present, it is printed out; otherwise, the user is requested to input it and alerted that it is missing. The new name-birthday pair is added to the lexicon. New names are added to the dictionary in the final output, validating the modification.

Similar square bracket syntax with the assignment operator is used to add a value to a dictionary. However, the dictionary key must be given in square brackets to designate where to add the new value.

Modifying Values in a Dictionary

We can easily update or modify the dictionary value by using the name of the dictionary, writing the key in square brackets, closing the brackets, and using the assignment operator (=) to assign the new value to the key. See the Python code for clarity.

First, we define a dictionary named ‘alien1’ in the code. After assigning the new value to the key ‘player name’ using the aforementioned instructions, we print the alien1 dictionary again and observe that the player name has changed from “Alex” to “Rohit”.

For a more complex situation, add the speed property to the "alien1" dictionary to track an alien with variable speed. In this configuration, we save the alien's speed and subsequently determine its ability to go in the appropriate direction.

At the start of the program, we declare a dictionary with x, y position, and speed keys and values. The alien2 dictionary's x position is printed next. If the speed key is sluggish, we create a variable named x_increment and set it to 5. We next verify if the speed key's value is ‘medium’ and utilize the x_increment variable again, this time with 10. Only the ‘fast’ speed remains after verifying the ‘slow’ and ‘medium’ speeds, therefore we use the else condition to put 15 on the x_increment variable. After testing the condition, we change the x_position by adding the current value and the condition value. Last, we report the updated x_position value to the output, showing the old and new values.

Removing Key-Value Pairs

When a dictionary item is unnecessary, we can use "del". It deletes a dictionary key-value pair. We specify the dictionary name and key to remove. This strategy is better explained with an example.

In the above code, we can see that before using the “del” statement we have three key-value pairs in the dictionary but when we use the “del” statement to remove the speed key and its value from the dictionary it removes it and we can verify this by printing the dictionary again.

A Dictionary of Similar Objects

We've mostly saved object-related information in dictionaries. Dictionaries may arrange and store homogeneous data about many things. Let's create a dictionary with comparable data entries.

The dictionary example shows a huge vocabulary arranged over numerous lines for clarity. The dictionary's keys are people's names and their values are their programming languages. For readability, such dictionaries must have a consistent indentation, especially when they span numerous lines. This includes naming the dictionary after the assignment operator, opening the brace, pushing enter, and indenting the next lines by one level (typically four spaces). Key-value pairs should be indented to match the initial pair and separated by commas. After finishing the dictionary, the closing brace is placed on a new line indented to match the key-value pairs. This layout assures dictionary definition clarity and structure. Examine a Python code sample to find which programming language each user likes.

In the above code, we first created a dictionary then we printed the output which shows Rohit’s favorite language using print statement.

The keys(), values(), and items() Methods

Keys(), values(), and items() are dictionary methods that return lists of keys, values, and key-value pairs. Please note that these methods do not return lists of values. They cannot be modified or appended like lists. Instead, they give iterable representations of the dictionary's keys, values, and objects without modifying the underlying dictionary. This difference preserves the dictionary's structure while making its components easy to retrieve. A for loop works with these data types. How does the for loop work with a dictionary?

The for loop in the code above iterates across all alien1 dictionary values. For loops can iterate over keys and key-value pairs. We pass keys to iterate.keys() with a dictionary in the for loop iterates key-value pairs.items() in the for loop.

The keys(), values(), and items() methods can loop over the dictionary's keys, values, and the entire key-value combination. Note that items() returns a key-value tuple. Tuples exist for every key and value.

To create a list from dictionary keys or values, we must feed its list-like return value to the list(). Let's see the Python code for clarity.

List() returns ['color', 'age'] from keys()'s dict_keys value in the list(spam.keys()) line. We may alternatively output values as a list using list().

In a for loop, we may assign keys and values to different variables using several assignment methods. This Python code should be examined.


In the above code, we can see that in the for loop we use two variables k, and v to iterate over the dictionary’s keys and values and print them using variables.

Checking Whether a Key or Value Exists in a Dictionary

The "in" and "not in" operators can be used to check dictionaries for a specific key or value. These operators make it easy to check for a key or value without iterating over the dictionary. If a key or value is in a dictionary, the "in" operation returns True; otherwise, False. The "not in" operator returns True if the key or value is not in the dictionary and False otherwise. This capability streamlines membership testing, making dictionaries more versatile. Like a list operation, we verify if a value is in the list. Take a peek at Python code to understand.


We employ “in” and “not in” operators in different scenarios in the aforementioned programs. The “key” “color” in the above dictionary is checked for spam keys first. It outputs True since it exists. The next code checks if ‘green’ is in the spam vocabulary and displays False because it is not. The next code uses the dictionary key. We verify ‘name’ in the spam dictionary keys in the fourth block. The code above outputs False if it is present and True otherwise. The same goes for dictionary values. The last piece of the code checks if ‘name’ is in the spam dictionary's key or value and outputs True if it is, False otherwise.

Python dictionary comprehension

An efficient and readable technique to build dictionaries with only one line of code is Python's dictionary comprehension.

The above creates a dictionary where the keys are numbers from 1 to 5, and the values are their squares. It is also the advanced dictionary in Python or we can say it is the advanced method to create a dictionary in Python.


The get() Method

It takes time to check if a key is in the dictionary before retrieving its value. Luckily, dictionaries provide a get() method that takes two parameters: the value to obtain and a backup value in case the key is incorrect. Take a peek at Python code to understand. We can also use the get() method for accessing values in the dictionary in Python.

We obtain 0 mangoes since there are no ‘mangoes’ in the picnicItems dictionary and we pass 0 to the get() function. Without the get() function, the code will create an error message like this:

The setdefault() Method
It is frequently necessary to set a value for a key in a dictionary only if it is empty. In normal technique, the code looks like the below demo. 

The "setdefault()" function can reduce this operation to one line of code, saving time. The second parameter defines the key to be checked and assigns a value if none exists. This method accepts two parameters. "setdefault()" puts the key-value pair into the dictionary and returns the value if the key is not in it. Adding new key-value pairs to the dictionary is easier with this method. We'll use the following code snippet to demonstrate this.

'color' is now associated with this value. When attempting to reassign the color using the setdefault() method to "white" in the subsequent line of code, the value of the key remains 'black'. This is because the dictionary already contains a key named 'color', and the setdefault() method does not alter existing key-value pairs.

The setdefault() method provides a convenient way to confirm the presence of a key within a dictionary. Consider a brief program demonstrating its usage to tally the occurrences of each letter within a string. 

The for loop of the program iterates over the string "message," counting each character's frequency. The setdefault() function checks if each character is a dictionary key and initializes it to 0 if not. This method avoids mistakes while incrementing character counts using count[character] = count[character] + 1.

The output shows character occurrences in the string. Two lowercase "c," thirteen space characters, and one uppercase "A" are visible.


Looping Through a Dictionary

Python dictionaries can store a few to millions of key-value pairs, making them adaptable data storage. Python has numerous dictionary iteration algorithms for varied datasets. You can cycle over all key-value pairs directly, iterate over keys or values separately, or use a mix of these to retrieve specific dictionary items.

Looping Through All Key-Value Pairs

As we saw before, we can retrieve dictionary key-value pairs using any key or value. Let's see both code examples. The code below loops over the dictionary's key and value and prints them. 

The code initializes a dictionary and iterates through its key-value pairs using a for loop. Two variables store each pair's key and value in the loop. Choose these variable names freely. This loop iterates across key-value pairs from the dictionary's items() function. The first variable stores the key, while the second stores the value. Key and value are shown using two print statements. This Python example shows how to retrieve and display dictionary contents. 

In the above code, we can see that we print the favorite programming language of the person using the same method we describe above.

Looping Through a Dictionary’s Keys in Order

While dictionaries lack a fixed order for their contents, this usually doesn't matter because keys can properly retrieve values. To retrieve keys in a specified sequence, they can be sorted first. The sorted() method sorts the dictionary's keys. Iterating over these sorted keys in a loop retrieves the items in order. This strategy is shown in the Python code below.

Note: -  the sorted() function can also sort the values of a dictionary just like keys. The code is also written below.

Nesting

Nesting dictionaries in a list or vice versa is sometimes needed. Nesting might entail embedding dictionaries or lists within dictionaries. Encapsulating a dictionary within another is conceivable. This layering capability is powerful in programming, but it's complicated to understand.


A list of Dictionaries

In this section, we will create a list of dictionaries in Python. Let's say we constructed a dictionary with a variety of information about one type of data or item, but it has no place for a second type, reducing data space. How do we handle this? Make a list of any dictionary-related variable and include all dictionary information in it. For example, let us have a dictionary called alien_0 with a certain type of information. If we want to store another alien_1 with the same information, we can create another dictionary to store its information, but if we have many alien dictionaries and want to show them all at once, we store them in a list and use a for-loop to print them. Let's examine Python code for clarity.

In the above code, we created three alien dictionaries that store the same data, so we cannot store them in one dictionary (which is a problem). Instead, we store them in three dictionaries, list them, and use a for loop to print them all at once.

A more realistic and practical example is automatically storing more than three alien dictionaries in the list. The example code below creates 30 aliens with the same key and value for speedy generation and stores them in an empty list.

As demonstrated above, we gave Python instructions to perform the for loop a specific number of times after creating an empty list by using the range() method. Each time the loop completes one iteration it creates a new dictionary called new_alien. Then in the next line with the help of the append() method, we add these created dictionaries to the aliens' dictionary.

In the next section of the code, we print the first five alien dictionaries from the alien's list using for loop, and at last, we print the total number of alien dictionaries we created to check that we have 30 new_alien dictionaries.

Let’s suppose from the above example some aliens change their color and move much faster as they progress. To accomplish this task, we utilize a combination of a for loop and if statement in the provided code. For instance, suppose we aim to alter the attributes of the first three aliens, changing their color from green to yellow, their speed from slow to medium, and their points from 5 to 10. By iterating through the list of aliens, we can implement these modifications based on specific conditions specified within the if statement. We can do this by adding the following lines code after we created and append all 30 aliens. For better understanding let’s write the whole code with this extra code.

A List in a Dictionary

When ordering pizza, a list may not convey enough information. A list could merely include toppings, excluding important subtleties. A dictionary provides a more complete description. A more complete pizza order might be represented by a dictionary with key-value pairs for crust type, toppings, size, and special instructions.

Consider a pizza shop that stores your dough and topping preferences. The dictionary value "toppings list" is connected with the key "toppings." Different values make up the toppings. Let's view the code for clarity. 

We constructed a dictionary called “pizza” to store order information in the above code. The pizza dictionary key ‘crust’ has the value ‘thick’. The next key value is a list. This list contains topping statistics. Before making the pizza, we summarize the order for print. As toppings have a list as a value, we must use the “for” loop to display and retrieve their key values.

When connecting several items with a single key, we can nest a list in a dictionary. For instance, update our preferred language dictionary. In this new dictionary, users may have many favorite languages. Our dictionary would assign each person a list of languages instead of one. We may go over each person's language using a nested for loop in the dictionary loop. This code sample shows:

The code shows that the dictionary keeps each key's (name) matching values. Certain keys, such as preferred language, contain single values, while others are listed. Each dictionary value is a list, therefore we use "languages" in the initial for loop to run over them. We use another for loop in the main loop to go through each person's favorite languages.

Note: Avoid deep nested lists and dictionaries. The examples show adequate layering, but excessive nesting can make code hard to comprehend and maintain. In such circumstances, simpler solutions are usually best.


A Dictionary in a Dictionary

Nesting dictionaries may easily complicate coding. Consider a website with several users with distinct usernames. In such circumstances, usernames can be dictionary keys. By providing a dictionary value to each username, we may keep user data. We save each user's location, last name, and first name in the example. Iterating across users and accessing their data dictionaries yields this data. Let's study this Python code:

The included code creates a dictionary called "users" with two keys: 'aeinstein' and 'mcurie'. Dictionary keys correlate first and last names, localities, and other data. One for loop iterates through the "users" dictionary. This loop stores each key in "username" and the dictionary associated with each username in "user_info". The first print() statement outputs the username. 

The code retrieves the user_info variable's internal dictionary after print(). This internal dictionary has "first," "last," and "location" keys. The code creates a name and location for each person using each key and then summarizes their information.

Summary

Python dictionaries, which use key-value pairs, are powerful and versatile data structures. Dictionaries differ from lists by enabling keys of any data type to correspond to specified values, marked by braces{}. Their dynamic information storage syntax allows applicability in numerous programming settings.

Like lists, dictionaries offer looping and quick item access. Key-value associations use the colon(:) within braces to indicate data connections cleanly and effectively. The “dict()” method initializes an empty dictionary.

In real-world applications, dictionaries properly model things using key-value pairs. Dictionary functions like looping and accessing values highlight dictionaries' versatility and efficiency in organizing and handling varied data sets.

Dynamic dictionaries offer smooth key-value pair addition using square brackets and the assignments operator. Dictionary order is immaterial, unlike lists, where order is necessary for equality.

Dictionaries differ from lists in ordering criteria, highlighting their uniqueness. Despite KeyError when handling missing keys, dictionaries are flexible enough to update birthdate information with user input.

This chapter shows how Python dictionaries may organize varied data types and be powerful programming tools. Dictionary looping and layered structures for complicated data situations enhance understanding of these dynamic data structures.

No comments:

Post a Comment

Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular