Python Dictionaries (With Example)

 PYTHON DICTIONARY:

A dictionary in Python is a versatile and powerful built-in data structure that allows you to store and organize data in key-value pairs. Each key is associated with a value, allowing you to efficiently retrieve, update, and manipulate data based on those keys. Dictionaries are also known as associative arrays or hash maps in other programming languages.

Python Dictionaries (With Example) | diplomawaale.blogspot.com

Dictionaries are commonly used for representing structured data, such as:

  • Storing configuration settings
  • Managing user data in applications
  • Representing JSON (JavaScript Object Notation) data
  • Counting occurrences of items

EXAMPLE:

                               # Creating a dictionary of student information
                               student = {
                                            "name": "John",
                                            "age": 20,
                                            "grade": "A",
                                            "courses": ["Math", "Science"]
                                           }

CREATING DICTIONARY:

You can create a dictionary in Python using curly braces '{}' and specifying key-value pairs separated by colons.

Here's a step-by-step explanation of creating a dictionary:


  1. Open a curly brace '{' to start the dictionary.
  2. Specify key-value pairs inside the dictionary. Each pair consists of a key followed by a colon: and then the associated value.
  3. Separate multiple key-value pairs with commas.
  4. Close the curly brace '}' to finish defining the dictionary.

EXAMPLE:

                                # Creating a dictionary of student information
                                student = {
                                                "name": "John",
                                                "age": 20,
                                                "grade": "A",
                                                "courses": ["Math", "Science"]
                                                }
                               # Creating an empty dictionary
                               employee = {}

                                # Adding key-value pairs
                                employee["name"] = "Alice"
                                employee["job"] = "Engineer"
                                employee["age"] = 28

ACCESSING VALUE FROM DICTIONARY:

You can access values from a dictionary in Python using the keys associated with those values.

EXAMPLE:

                            # Creating a dictionary
                            student = {
                                    "name": "John",
                                    "age": 20,
                                    "grade": "A",
                                    "courses": ["Math", "Science"]
                                 }

                           # Accessing values using keys
                           student_name = student["name"]     # Access value using the key "name"
                           student_age = student["age"]       # Access value using the key "age"
                           student_courses = student["courses"]  # Access value using the key "courses"

                           # Printing the accessed values
                           print("Student Name:", student_name)
                           print("Student Age:", student_age)
                           print("Student Courses:", student_courses)

If you try to access a key that doesn't exist in the dictionary, it will raise a KeyError. To avoid this, you can use the '.get()' method.

EXAMPLE:

                        student_grade = student.get("grade", "Not Available")
                        print("Student Grade:", student_grade)

BUILT-IN DICTIONARY FUNCTION:

Sr.No.

Function with Description

1

cmp(dict1, dict2)

Compares elements of both dicts.

2

len(dict)

Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

3

str(dict)

Produces a printable string representation of a dictionary

4

type(variable)

Returns the type of the passed variable. If a passed variable is a dictionary, then it would return a dictionary type.

 

BUILT-IN METHOD IN DICTIONARY:

Sr.No.

Methods with Description

1

dict.clear()

Removes all elements of the dictionary dict

2

dict.copy()

Returns a shallow copy of the dictionary dict

3

dict.fromkeys()

Create a new dictionary with keys from seq and values set to value.

4

dict.get(key, default=None)

For key, returns value or default if key not in the dictionary

5

dict.has_key(key)

Returns true if key in dictionary dictfalse otherwise

6

dict.items()

Returns a list of dict's (key, value) tuple pairs

7

dict.keys()

Returns list of dictionary dict's keys

8

dict.setdefault(key, default=None)

Similar to get(), but will set dict[key]=default if the key is not already in the dict

9

dict.update(dict2)

Adds dictionary dict2's key-values pairs to dict

10

dict.values()

Returns list of dictionary dict's values

                                           CREDITED BY @DiplomaWale




Post a Comment

0 Comments