#Day 15 Python Dict.{} []

Dictionary (dict)

In Python, a dictionary is a built-in data type used to store collections of key-value pairs. It's like a real-life dictionary where you look up a word (the key) to find its definition (the value). Let's explore this concept with a real-life example:

Imagine you have a contacts list where you store information about your friends. Each friend has a name (the key) and their phone number (the value). You can use a Python dictionary to represent this contacts list:

In this dictionary:

  • Each friend's name (e.g., "Alice", "Bob") is a key.

  • Each friend's phone number (e.g., "555-1234", "555-5678") is the corresponding value.

Now, if you want to find Bob's phone number, you can simply look it up in the dictionary:

Output:

You can also add new contacts or update existing ones easily:

Output:

Task 1 - Create a Dictionary in Python and write it to a json File.

In this example:

  • We import the json module, which provides functions for working with JSON data.

  • We create a dictionary called my_dict containing some key-value pairs.

  • We specify the file path where we want to save the JSON file (in this case, "my_dict.json").

  • We use the open() function with the mode "w" (write mode) to open the file for writing.

  • We use the json.dump() function to write the contents of my_dict to the JSON file.

  • Finally, we print a message to confirm that the dictionary has been written to the JSON file.

After running this code, you'll find a file named "my_dict.json" in the same directory as your Python script, containing the contents of the dictionary in JSON format.


Thank you for joining me on this journey into DevOps! Your curiosity is the driving force behind this exploration. If you found value in these insights, I'm thrilled! Keep the DevOps flame alive, and stay tuned for more exciting adventures in the world of technology. Happy Learning! 🚀✨"

"Closing the gap between us—let's connect and make our virtual bond stronger on social media!

Click on -Umesh Salunkhe