Dictionaries in Python are an ordered collection of key-value pairs. They allow you to store multiple items in a single variable. Dictionary items are enclosed within curly brackets {} and separated by commas.
Creating a dictionary:
info = {'name': 'Ken', 'age': 19, 'eligible': True}
print(info)
Output:
{'name': 'Ken', 'age': 19, 'eligible': True}
Accessing single values using keys:
info = {'name': 'Ken', 'age': 19, 'eligible': True}
print(info['name'])
print(info.get('eligible'))
Output:
Ken
True
Accessing multiple values using values()
:
info = {'name': 'Ken', 'age': 19, 'eligible': True}
print(info.values())
Output:
dict_values(['Ken', 19, True])
Accessing keys using keys()
:
info = {'name': 'Ken', 'age': 19, 'eligible': True}
print(info.keys())
Output:
dict_keys(['name', 'age', 'eligible'])
Accessing key-value pairs using items()
:
info = {'name': 'Ken', 'age': 19, 'eligible': True}
print(info.items())
Output:
dict_items([('name', 'Ken'), ('age', 19), ('eligible', True)])
dict.fromkeys()
: Creating a Dictionary with Default Values
keys = ['a', 'b', 'c']
default_value = 0
my_dict = dict.fromkeys(keys, default_value)
print(my_dict)
Output:
{'a': 0, 'b': 0, 'c': 0}
This method is particularly useful when you need to initialize a dictionary with a common default value for multiple keys.
Using the update()
Method: The update()
method allows you to merge the contents of another dictionary into the one created with fromkeys()
. Here's how you can use it:
my_dict = dict.fromkeys(['a', 'b', 'c'], 0)
new_dict = {'b': 2, 'd': 4}
my_dict.update(new_dict) # Update my_dict with key-value pairs from new_dict
After the update, my_dict
will look like this:
{'a': 0, 'b': 2, 'c': 0, 'd': 4}
Conclusion
Python dictionaries are versatile data structures that store key-value pairs. They provide efficient access to values using keys. With curly brackets and commas, dictionaries are easy to create and manipulate. Accessing values, keys, or key-value pairs is straightforward using built-in methods like values()
, keys()
, and items()
. Dictionaries empower you to efficiently organize and retrieve data, making them a valuable tool in Python programming.