Dictionary Methods
Dictionaries come with several handy methods such as setdefault, update, pop, popitem, and clear.
my_dict = {'name': 'Alice', 'age': 25}
# setdefault
my_dict.setdefault('city', 'Unknown')
print(my_dict)
# update
my_dict.update({'age': 26, 'city': 'New York'})
print(my_dict)
# pop
age = my_dict.pop('age')
print(age) # Output: 26
print(my_dict)
# popitem
item = my_dict.popitem()
print(item)
print(my_dict)
# clear
my_dict.clear()
print(my_dict)
#clcoding.com
{'name': 'Alice', 'age': 25, 'city': 'Unknown'}
{'name': 'Alice', 'age': 26, 'city': 'New York'}
26
{'name': 'Alice', 'city': 'New York'}
('city', 'New York')
{'name': 'Alice'}
{}
Ordered Dictionaries
As of Python 3.7, dictionaries maintain insertion order by default. The OrderedDict from the collections module was used for this purpose in earlier versions.
my_dict = {'first': 1, 'second': 2, 'third': 3}
print(my_dict)
#clcoding.com
{'first': 1, 'second': 2, 'third': 3}
Merging Dictionaries
Starting with Python 3.9, you can use the | operator to merge dictionaries.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
print(merged_dict)
#clcoding.com
{'a': 1, 'b': 3, 'c': 4}
Dictionary Views
The keys, values, and items methods return dictionary view objects, which are dynamic and reflect changes in the dictionary.
my_dict = {'name': 'Alice', 'age': 25}
keys_view = my_dict.keys()
print(keys_view)
my_dict['city'] = 'New York'
print(keys_view)
#clcoding.com
dict_keys(['name', 'age'])
dict_keys(['name', 'age', 'city'])
Default Values with get and defaultdict
Using the get method, you can provide a default value if the key is not found.
my_dict = {'name': 'Alice'}
print(my_dict.get('age', 'Not Found'))
Not Found
With defaultdict from the collections module, you can provide default values for missing keys.
from collections import defaultdict
dd = defaultdict(int)
dd['a'] += 1
print(dd)
#clcoding.com
defaultdict(<class 'int'>, {'a': 1})
Dictionary Comprehensions
Just like list comprehensions, you can create dictionaries using dictionary comprehensions.
squares = {x: x*x for x in range(6)}
print(squares)
#clcoding.com
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Iterating Through Dictionaries
You can iterate through keys, values, or key-value pairs in a dictionary.
my_dict = {'name': 'Alice', 'age': 25}
for key in my_dict:
print(key)
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(key, value)
#clcoding.com
name
age
Alice
25
name Alice
age 25
Keys Must Be Immutable and Unique
The keys in a dictionary must be immutable types (like strings, numbers, or tuples) and must be unique.
my_dict = {(1, 2): 'tuple key', 'name': 'Alice', 3.14: 'pi'}
print(my_dict)
#clcoding.com
{(1, 2): 'tuple key', 'name': 'Alice', 3.14: 'pi'}
Efficient Lookup Time
Dictionaries have average O(1) time complexity for lookups, insertions, and deletions due to their underlying hash table implementation.
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict['b'])
#clcoding.com
2
Dynamic and Mutable
Dictionaries are mutable, which means you can change their content without changing their identity.
my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26
my_dict['city'] = 'New York'
print(my_dict)
#clcoding.com
{'name': 'Alice', 'age': 26, 'city': 'New York'}
0 Comments:
Post a Comment