Dictionary Methods with Python

Dictionary Methods

clear()

Description: Removes all items from the dictionary.

Example

my_dict.clear()
print(my_dict)  # Outputs {}

 copy()

Description: Returns a shallow copy of the dictionary.

Example

dict_copy = my_dict.copy()
print(dict_copy)  # Outputs {'name': 'Alice', 'age': 30, 'city': 'Paris'}

fromkeys(seq, value)

Description: Creates a new dictionary with keys from seq and the value value for each key.

Example

keys = ['a', 'b', 'c']
default_value = 0
new_dict = dict.fromkeys(keys, default_value)
print(new_dict)  # Outputs {'a': 0, 'b': 0, 'c': 0}

 get(key, default)

Description: Returns the value for key if key is in the dictionary. If not, returns default.

Example

value = my_dict.get('name')
print(value)  # Outputs 'Alice'
unknown_value = my_dict.get('unknown', 'Not defined')
print(unknown_value)  # Outputs 'Not defined'

items()

Description: Returns a view of the dictionary’s key-value pairs.

Example

pairs = my_dict.items()
print(pairs)  # Outputs dict_items([('name', 'Alice'), ('age', 30), ('city', 'Paris')])

keys()

Description: Returns a view of the dictionary’s keys.

Example

keys = my_dict.keys()
print(keys)  # Outputs dict_keys(['name', 'age', 'city'])

pop(key, default)

Description: Removes the item with key and returns its value. If key is not found, returns default.

Example

value_removed = my_dict.pop('age')
print(value_removed)  # Outputs 30
print(my_dict)  # Outputs {'name': 'Alice', 'city': 'Paris'}
# With default value
missing_value = my_dict.pop('unknown', 'Not found')
print(missing_value)  # Outputs 'Not found'

popitem()

Description: Removes and returns a key-value pair from the dictionary. In Python 3.7+, it removes the most recently added pair.

Example

item = my_dict.popitem()
print(item)  # Outputs ('city', 'Paris')
print(my_dict)  # Outputs {'name': 'Alice'}

 setdefault(key, default)

Description: Returns the value for key if key is in the dictionary. If not, inserts key with the default value and returns default.

Example

value = my_dict.setdefault('country', 'France')
print(value)  # Outputs 'France'
print(my_dict)  # Outputs {'name': 'Alice', 'country': 'France'}

update([other])

Description: Updates the dictionary with key-value pairs from another dictionary or iterable of key-value pairs.

Example

new_elements = {'age': 31, 'profession': 'Engineer'}
my_dict.update(new_elements)
print(my_dict)  # Outputs {'name': 'Alice', 'country': 'France', 'age': 31, 'profession': 'Engineer'}

 values()

Description: Returns a view of the dictionary’s values.

Example

values = my_dict.values()
print(values)  # Outputs dict_values(['Alice', 'France', 31, 'Engineer'])

 Dictionary Manipulation

Here are some common manipulations you might find useful:

Adding or Modifying an Element 

my_dict['email'] = 'alice@example.com'  # Adding
my_dict['age'] = 31  # Modifying
print(my_dict)  # Outputs {'name': 'Alice', 'country': 'France', 'age': 31, 'profession': 'Engineer', 'email': 'alice@example.com'}

Removing an Element 

del my_dict['email']
print(my_dict)  # Outputs {'name': 'Alice', 'country': 'France', 'age': 31, 'profession': 'Engineer'}

Practical Examples

Counting Character Occurrences 

text = "hello"
counter = {}
for char in text:
    counter[char] = counter.get(char, 0) + 1
print(counter)  # Outputs {'h': 1, 'e': 1, 'l': 2, 'o': 1}

Merging Two Dictionaries 

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)  # Outputs {'a': 1, 'b': 3, 'c': 4}

Conclusion

Dictionaries in Python are extremely versatile, and their methods allow for effective data manipulation. I hope this lesson has provided a good understanding of the available methods and how to use them. Feel free to experiment and explore further to fully master dictionaries in Python.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Facebook
Twitter
LinkedIn
WhatsApp
Email
Print