Dictionaries in Python are powerful data structures that store key-value pairs. They offer efficient data retrieval and organization, making them essential for representing real-world objects and managing complex data relationships. This unit covers dictionary creation, accessing values, and common operations. It also explores nested dictionaries, comprehensions, and advanced techniques like sorting and using specialized dictionary classes from the collections module.
{}
with each key-value pair separated by a comma{}
or the dict()
constructor:
to separate the key from its corresponding value[]
KeyError
get()
method can be used to retrieve a value by its key, returning a default value if the key is not found
dictionary.get(key, default_value)
dictionary[key] = value
len(dictionary)
returns the number of key-value pairs in the dictionarydictionary.keys()
returns a view object containing all the keys in the dictionarydictionary.values()
returns a view object containing all the values in the dictionarydictionary.items()
returns a view object containing all the key-value pairs as tuplesdictionary.update(other_dictionary)
merges the key-value pairs from other_dictionary
into the original dictionarydictionary.pop(key)
removes and returns the value associated with the specified key, raising a KeyError
if the key is not founddictionary.clear()
removes all key-value pairs from the dictionary, leaving it emptydel dictionary[key]
removes the key-value pair with the specified key from the dictionarykey in dictionary
checks if a key exists in the dictionary, returning True
or False
get()
method for each level
employee_data[employee_id]['personal_info']['address']
{}
and a key-value pair definition{key_expression: value_expression for item in iterable if condition}
if
condition is optional and filters the items from the iterableword_count = {word: text.count(word) for word in set(text.split())}
sorted()
function and a key function
sorted(dictionary.items(), key=lambda x: x[1])
sorts the dictionary by valuesdefaultdict
from the collections
module automatically initializes missing keys with a default value or factory function
Counter
class from the collections
module is a subclass of dict
used for counting hashable objects
most_common()
to retrieve the most common elements and their countsjson
module for data exchange or storage
json.dumps(dictionary)
converts a dictionary to a JSON stringjson.loads(json_string)
converts a JSON string back to a dictionary