4 Important Dictionary Methods

Hello everybody, I'm Aya Bouchiha, today, we'll talk about 4 important dictionary methods.

clear()

clear(): this method lets you delete all the dictionary's items;

user = {
  "name": "Aya Bouchiha",
  "email":"[email protected]",
}

print(len(user)) # 2
user.clear()
print(user) # {}
print(len(user)) # 0

copy()

copy(): lets you get a copy of the specified dictionary.

user = {
  "name": "Aya Bouchiha",
  "email":"[email protected]",
}

admin = user.copy()
# {'name': 'Aya Bouchiha', 'email': '[email protected]'}
print(admin)
user['name'] = 'John Doe'
# {'name': 'John Doe', 'email': '[email protected]'}
print(user)
# {'name': 'Aya Bouchiha', 'email': '[email protected]'}
print(admin)

setdefault(key, value)

setdefault(key, value(optional)): this method returns the value of the given key If It exists, otherwise, It creates a new item with the given key and value and returns its value.

user = {
  "name": "Aya Bouchiha",
  "email":"[email protected]",
}


print(user.setdefault('name', 'unknown')) # Aya Bouchiha
print(user.setdefault('is_admin', 'False')) # False

# {'name': 'Aya Bouchiha', 'email': '[email protected]', 'is_admin': 'False'}
print(user)

values()

values(): this method returns all the given dictionary's values as a list.

products_prices_in_dollar = {
  "laptop":1000,
  "phone":150,
  "mouse":10,
  "keyboard":7
}
print(products_prices_in_dollar.values()) # dict_values([1000, 150, 10, 7])

# converts from dollar to moroccan dirham
# 1000+150+10+7 = 1167$ => 11670 moroccan dirhams
sum_in_dirham = sum(products_prices_in_dollar.values()) * 10

# you have to pay 11670 dirhams
print(you have to pay {sum_in_dirham} dirhams')

Summary

  • clear(): deletes all the dictionary's items;
  • copy(): returns a copy of the specified dictionary.
  • setdefault(): returns the value of the given key If It exists, otherwise, It create a new item with the given key and value and returns its value.
  • values():returns all the given ditionary's values as a list

Reference

Suggested posts

To Contact Me:

telegram: Aya Bouchiha

Hope you enjoyed reading this post :)

11