Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Dictionary Program in Python

Last Updated on June 6, 2024 by Abhishek Sharma

Python dictionaries are a powerful and versatile data structure that allows you to store and manipulate data in key-value pairs. Unlike lists, which are indexed by a range of numbers, dictionaries are indexed by unique keys, which can be strings, numbers, or other immutable types. This makes dictionaries incredibly useful for a variety of programming tasks, such as organizing data, counting occurrences, or mapping one set of values to another.

In a dictionary, each key is mapped to a value, and you can efficiently retrieve, update, and delete values based on their keys. The ability to use meaningful keys instead of numerical indices makes dictionaries a preferred choice when working with large datasets or when the relationship between data elements needs to be clear and easily understandable.

What is a Dictionary?

A dictionary in Python is a collection of key-value pairs. The keys in a dictionary must be unique and immutable, while the values can be any data type. Dictionaries are often used to represent real-world objects, such as a person or a car. In Python, dictionaries are implemented using curly braces {} and colons :. Here is an example of a dictionary:

Creating a Dictionary in Python

To create a dictionary in Python, you simply need to define the keys and values inside curly braces {}.

Let us create a dictionary to represent a person, with the keys being "name", "age", "address", and "phone number", and the values being the actual data.

Code:

# creating dictionary
person = {"name": "PrepBuddy", "age": 18, "address": "Delhi", "phone number": "5575-1234"}


# printing dictionary
print(person)

Output:

{'name': 'PrepBuddy', 'age': 18, 'address': 'Delhi', 'phone number': '5575-1234'}

Explanation:
In this example, we created a dictionary called "person" with the keys "name", "age", "address", and "phone number", and the values "PrepBuddy", 18, "Delhi", and "5575-1234", respectively. We then printed the dictionary using the print() function.

Accessing Values in Dictionary

To access a value in a dictionary, we can use the key as the index.

Code:

# creating dictionary
person = {"name": "PrepBuddy", "age": 18, "address": "Delhi", "phone number": "5575-1234"}


# Accessing the value of the "name" key
print(person["name"])

Output:

PrepBuddy

Explanation:
In the above example, we accessed the value of the "name" key in the "person" dictionary by using "name" as the index. We get the output as “PrepBuddy”.

Adding Values in a Dictionary

We can add a new key-value pair to a dictionary by simply assigning a value to a new key. This will be more clear from the following code.

Code:

# creating dictionary
person = {"name": "PrepBuddy", "age": 18}


# printing initial dictionary
print("Initial Dictionary: ", person)


# Adding a new key-value pair
person["address"] = "Delhi"


# Printing the updated dictionary
print("Updated Dictionary: ", person)

Output:

Initial Dictionary:  {'name': 'PrepBuddy', 'age': 18}
Updated Dictionary:  {'name': 'PrepBuddy', 'age': 18, 'address': 'Delhi'}

Explanation:
In the above code, we first created a dictionary named “person” and printed it on the screen. Then we add a new key-value pair with “address” as the key and “Delhi” as the value. Finally, we printed the updated dictionary on the screen.

Modifying Values in a Dictionary

We can also modify the values present in the dictionary. To modify the value of an existing key in a dictionary, we simply need to assign a new value to the key. Here is the code demonstrating the modification of values in a dictionary.

Code:

# creating dictionary
person = {"name": "PrepBuddy", "age": 18}


# printing initial dictionary
print("Initial Dictionary: ", person)


# Modifying dictionary
person["age"] = 20


# Printing the updated dictionary
print("Updated Dictionary: ", person)

Output:

Initial Dictionary:  {'name': 'PrepBuddy', 'age': 18}
Updated Dictionary:  {'name': 'PrepBuddy', 'age': 20}

Explanation:
In the above code, we modified the value of the “age” key from 18 to 20. This shows we can easily modify the elements of the dictionary in Python. We have printed the dictionary before and after modification to show the changes that are made.

Iterating through a Dictionary

Dictionary in Python can be iterated by using the for loop. Here is how to use the for loop for iterating over the dictionary.

Code:

# creating dictionary
person = {"name": "PrepBuddy", "age": 18, "address": "Delhi"}


# Iterating over dictionary
for key, value in person.items():
    print(key + ": " + str(value))

Output:

name: PrepBuddy
age: 18
address: Delhi

Explanation:
In the above code, we used a for loop to iterate through the "person" dictionary. We used the items() method to get a list of key-value pairs in the dictionary and then printed each key and value on a separate line.

Deleting Key-Value Pairs from a Dictionary

We can also delete a key-value pair from a dictionary in Python. For deleting key-value pairs, we use the del statement.

Code:

# creating dictionary
person = {"name": "PrepBuddy", "age": 18, "address": "Delhi"}


# printing initial dictionary
print("Initial Dictionary: ", person)


# deleting key-value pair
del person["address"]


# Printing the updated dictionary
print("Updated Dictionary: ", person)

Output:

Initial Dictionary:  {'name': 'PrepBuddy', 'age': 18, 'address': 'Delhi'}
Updated Dictionary:  {'name': 'PrepBuddy', 'age': 18}

Explanation:
In this example, we used the del statement to delete the "address” key-value pair from the "person" dictionary.

Conclusion
Python dictionaries are an essential data structure that offers flexibility, efficiency, and ease of use for a wide range of programming tasks. Understanding how to create, manipulate, and operate on dictionaries is crucial for any Python programmer. This guide has covered common questions and answers related to dictionary programming in Python, providing practical examples and insights into their usage.

By mastering dictionaries, you can handle more complex data structures, improve your problem-solving skills, and write more efficient and readable code. As you continue to explore Python and its powerful features, keep practicing with dictionaries and experimenting with different techniques to deepen your understanding and enhance your programming capabilities.

Frequently Asked Questions(FAQs) Related to Dictionary in Python:

Here are some frequently asked questions on the Dictionary program in Python.

1. How is a dictionary different from a list in Python?

  • Dictionary: An unordered collection of key-value pairs. Keys must be unique and immutable. Used when you need a logical association between a key pair and for fast retrieval.
  • List: An ordered collection of elements. Elements can be accessed by their index. Used when you need an ordered collection of items.

2. Can dictionary keys be of any data type?
No, dictionary keys must be of an immutable data type. Common examples include strings, numbers, and tuples. Keys must also be unique within a dictionary.

3. How does Python handle dictionary collisions?
Python handles dictionary collisions using a method called chaining. When a hash collision occurs, it stores multiple key-value pairs in the same "bucket" and maintains a list of pairs for each bucket.

4. What are some common operations you can perform on dictionaries?
Common dictionary operations include:

  • Accessing values by key
  • Adding and updating key-value pairs
  • Deleting key-value pairs
  • Iterating over keys, values, or items
  • Checking for the existence of keys
  • Merging dictionaries

5. What are some use cases for dictionaries in Python?
Dictionaries are used in a variety of scenarios, including:

  • Storing and managing configuration settings: Easily accessible and updatable settings.
  • Counting occurrences of items: Using keys as items and values as counts.
  • Implementing lookup tables: Fast retrieval of associated values.
  • Representing JSON-like data structures: Parsing and generating JSON data.
  • Organizing data with meaningful associations: Creating mappings between related data points.

Leave a Reply

Your email address will not be published. Required fields are marked *