top of page
Search
  • Writer's pictureMaia

Python Tips Series: Dictionary


Dictionary is indeed one of the most important data types and data structure in Python. That's probably true for any other programming languages too. We can see dictionaries everywhere in the Python language implementation itself and in any Python application.

For example, the Python's globals() and locals() functions that store all global and local identities are actually just dictionaries.

Therefore, understanding this data structure well and its common methods is very key to fluency of Python language.

So, what is a dictionary. A dictionary is is container that contains zero or more item. Each item is a key/value pair. The key is any hashable object and the value can be any object including another dictionary. Each key in a dictionary is unique, meaning there can't be more than one identical key. Items in dictionary are not ordered, not like lists or tuples.

Now, let's create some dictionary.

Notice that, even though most of the objects can be a key for a dictionary, but not all. For example, a list can't be dictionary keys.

However, tuples can be used as dictionary keys.

We can also create a dict using the dict() function if all the keys are just strings.

How to add a new item to a dict? Easy. We can use a square bracket [] syntax and provide key and value. If the key provided is not in the dict, it will add it as a new key/value pair.

How about update an existing item? Same thing, we can do the same as above if the key already exists it will be replaced with new value provided.

To access an item from the dict, we normally use its key with the same square bracket syntax above. But if the key provided does not exist it will raise a KeyError exception.

To avoid this kind of exception when we don't know if a key exists, we can use the dictionary method get() and we can even provide a default value in case it doesn't exist it will return that default value.

The most commonly used functions of dictionary are:

- keys() : to get all keys - normally to loop through them

- values(): to get all values

- items(): to get all key/value pairs

More often when we iterate through a dict to get its items we unpack key/value as the same time.


That are the key concept about dictionary that every Python programmer must understand because it is used everyday.

To keep this short and relevant, I will com back in another article for more in-depth of using dictionary like updating, sorting dictionaries.


Happy programming!



Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page