Dictionaries are an unordered collection of items. Each item in a dictionary is stored as a key-value pair, where each key is unique and associated with a corresponding value. Dictionaries are mutable, meaning they can be modified after creation.
Basics of Dictionaries
In Python, dictionaries are defined by using curly braces ‘{}'
and key-value pairs separated by colons ':'
.
For example:
1 2 3 4 5 | data: dict = { "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", } |
You can access the value associated with a specific key using square brackets ‘[ ]’:
1 2 3 4 5 6 7 8 9 | data: dict = { "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", } print(data["key_1"]) >>> value_1 |
Dictionary’s Capabilities & Limitations
Mutablility : We can add a new key, modify value or delete key-value pairs:
1 2 3 4 5 6 7 8 9 | data: dict = { "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", } data["key_1"] = "new_value" del data["key_2"] data["new_key"] = "new_key_value" |
Duplicates Not Allowed: Dictionaries cannot have two items with the same key:
1 2 3 4 5 6 | person = { "full_name": "joe doe", "age": "37", "job": "doctor", "job": "personal trainer" } |
When defining a dictionary, if a key is duplicated, the latest occurrence will overrides the previous one.
Allows Different Data Types: Dictionaries allows define different typed key-value pairs.
1 2 3 4 5 6 7 8 | person = { "full_name": "joe doe", "age": 37, "jobs": ["doctor", "personel trainer"], "working": True, "married": False, "child": ("Alice", "Bob") } |
1 2 3 4 5 6 7 | order = { 1: "a", 2: "b", 3: "c", 4: "d", 5: "Undefined" } |
Dict Constructor : The dict() constructor provides make a dictionary by args.
1 2 3 4 | test_dict_constructor = dict(full_name = "joe doe", age = 36, working = True) print(test_dict_constructor) >>> {'full_name': 'joe doe', 'age': 36, 'working': True} |
Non Restricted Values : There is no restriction on dictionaries values. You can define same values for different keys or you can define any dataype.
Built-in Dictionary Methods
- dict.clear(): Clears ditionary object’s memory and resets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | order = { 1: "a", 2: "b", 3: "c", 4: "d", 5: "Undefined" } print(order) >>> {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'Undefined'} order.clear() print(order) >>> {} |
- dict.get(“key” [,”default”]): Searchs related key and returns, if there is not exists related key returns None or defined value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | person = { "name": "joe", "surname": "doe", } print(person.get("name")) >>> joe print(person.get("surname")) >>> doe print(person.get("age", 0)) >>> 0 |
- dict.keys(): Returns a list of all the keys in the dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | person = { "name": "joe", "surname": "doe", "age": 37, "working": False } print(person.keys()) >>> dict_keys(['name', 'surname', 'age', 'working']) print(list(person.keys())) >>> ['name', 'surname', 'age', 'working'] |
- dict.values(): Returns a list of all the values in the dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | person = { "name": "joe", "surname": "doe", "age": 37, "working": False } print(person.values()) >>> dict_values(['joe', 'doe', 37, False]) print(list(person.values())) >>> ['joe', 'doe', 37, False] |
- dict.items(): This method returns a list of key-value tuple pairs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | person = { "name": "joe", "surname": "doe", "age": 37, "working": False } print(person.items()) >>> dict_items([('name', 'joe'), ('surname', 'doe'), ('age', 37), ('working', False)]) print(person.items()) >>> [('name', 'joe'), ('surname', 'doe'), ('age', 37), ('working', False)] |
- dict.pop(“key”): Removes and returns the value associated with the specified key. If the key is not found, it returns the specified default value (or raises a KeyError if not specified).
1 2 3 4 5 6 7 8 9 10 11 | person = { "name": "joe", "surname": "doe", "age": 37, "working": False } value = person.pop('name') print(value) >>> joe |
- dict.update(new_data: dict) : Updates the dictionary with the key-value pairs from the specified iterable (such as another dictionary or a list of tuples).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | person = { "name": "joe", "surname": "doe", "age": 37, "working": False } person.update({'name': "bob"}) print(person) >>> {'name': 'bob', 'surname': 'doe', 'age': 37, 'working': False} person.update({'name': "alice", "age": 24}) print(person) >>> {'name': 'alice', 'surname': 'doe', 'age': 24, 'working': False |
Summary
In Python, dictionary data types are versatile data structures that enable store data and manipulation data through key-value pairs. Dictionaries offers a flexible and dynamic way to organize and work with data, allowing for quick lookups based on unique keys. With built-in methods and operations, dictionaries facilitate various data processing tasks, making them invaluable tools in Python programming. Whether handling configurations, representing relationships, or managing data, dictionaries provide a convenient and powerful solution for a wide range of applications.