course content

Course Content

Introduction to Python

Dictionary MethodsDictionary Methods

As you may have noticed, dictionaries differ from lists and tuples. So do their methods. Let's consider them.

  • len(d) - returns the length of dictionary d (number of pairs key:value)
  • d.copy() - returns a copy of dictionary d
  • d.items() - returns all pairs (key, value) in dictionary d
  • d.keys() - returns all keys of dictionary d
  • d.values() - returns all values of dictionary d

How do you add new data to a dictionary? Unlike lists or tuples, neither .append()/.extend() methods nor concatenation works. Since dictionaries store data in pairs, we can add new data by keys:

  • d[k] = e - sets value e to the key k. If key k is in existing keys, then the value will be rewritten

For instance, traditionally, let's update our dictionary with two countries:

Section 4.

Chapter 12