DEV Community

Cover image for 4 Important Dictionary Methods
Aya Bouchiha
Aya Bouchiha

Posted on

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":"developer.aya.b@gmail.com",
}

print(len(user)) # 2
user.clear()
print(user) # {}
print(len(user)) # 0
Enter fullscreen mode Exit fullscreen mode

copy()

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

user = {
  "name": "Aya Bouchiha",
  "email":"developer.aya.b@gmail.com",
}

admin = user.copy()
# {'name': 'Aya Bouchiha', 'email': 'developer.aya.b@gmail.com'}
print(admin)
user['name'] = 'John Doe'
# {'name': 'John Doe', 'email': 'developer.aya.b@gmail.com'}
print(user)
# {'name': 'Aya Bouchiha', 'email': 'developer.aya.b@gmail.com'}
print(admin)
Enter fullscreen mode Exit fullscreen mode

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":"developer.aya.b@gmail.com",
}


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

# {'name': 'Aya Bouchiha', 'email': 'developer.aya.b@gmail.com', 'is_admin': 'False'}
print(user)
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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:

email: developer.aya.b@gmail.com

telegram: Aya Bouchiha

Hope you enjoyed reading this post :)

Top comments (0)