From the course: Programming Foundations: Algorithms

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Value counting with a dictionary

Value counting with a dictionary - Python Tutorial

From the course: Programming Foundations: Algorithms

Value counting with a dictionary

- [Instructor] Because the dictionary data structure requires that keys be unique, we can easily use it to implement an algorithm that counts individual items. So remember that a dictionary is conceptually a two-dimensional array of keys and associated values. Each key has to be unique, but the value associated with a key can be anything. So to create a counter, we can simply create a new dictionary, and then loop over the set of items that we want to count. We can use the name of each item as a key, and if the item already exists in the dictionary, then we increment the value that the key corresponds to. Otherwise, we set the value of the key with that item name equal to one. So after we've iterated over all the items, the counter will contain unique keys that represent all the items along with the number of times that that item was encountered. And, just like in the previous example, this one also has a big O of…

Contents