Python's dictionary is a powerful data structure that stores key-value pairs. It's like a real-world dictionary where you can look up words (keys) to find their...

Python's dictionary is a powerful data structure that stores key-value pairs. It's like a real-world dictionary where you can look up words (keys) to find their meanings (values). In this guide, we'll delve into the syntax of Python dictionaries, helping you understand and utilize them effectively.

You can create a dictionary using curly braces {} and separating keys and values with a colon :. Here's a simple example:

my_dict = {"name": "John", "age": 30, "city": "New York"}
In this dictionary, 'name', 'age', and 'city' are keys, and 'John', 30, and 'New York' are their respective values.

Python also provides a built-in function, dict(), to create dictionaries. It's useful when you have a list of tuples where each tuple is a key-value pair:
my_dict = dict([("name", "John"), ("age", 30), ("city", "New York")])
You can access dictionary values using their keys. If the key is not found, Python will raise a KeyError. To avoid this, you can use the get() method, which returns None or a default value if the key is not found:

print(my_dict["name"]) # Output: John
print(my_dict.get("country")) # Output: None
print(my_dict.get("country", "Unknown")) # Output: Unknown
You can add new key-value pairs or modify existing ones using the assignment operator:
my_dict["country"] = "USA" my_dict["age"] = 31

Python provides the update() method to add or modify multiple key-value pairs at once:
my_dict.update({"country": "USA", "job": "Engineer"})




















You can remove key-value pairs using the del statement or the pop() method:
del my_dict["age"]
my_dict.pop("country")
To remove all key-value pairs, you can use the clear() method:
my_dict.clear()
Python dictionaries come with several built-in methods. Here's a table summarizing some of the most useful ones:
| Method | Description |
|---|---|
len() |
Returns the number of key-value pairs. |
keys() |
Returns a view object that displays a list of all keys. |
values() |
Returns a view object that displays a list of all values. |
items() |
Returns a view object that displays a list of all key-value tuples. |
copy() |
Returns a shallow copy of the dictionary. |
Dictionaries can be nested within other dictionaries to create complex data structures. Here's an example:
user = {
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
}
In this example, the 'address' key has a dictionary as its value, allowing us to store more complex data.
That's it! You now have a solid understanding of Python dictionary syntax. Happy coding!