Dictionaries in Python Explained
Tags: beginners, webdev, python, programming
Published: 2023-05-31 17:01:20

Dictionaries in Python are a versatile data structure that allows for efficient and flexible data management. In this article, I would like to explain to you how dictionaries work in Python.

## What are Dictionaries?
A dictionary in Python is a collection of key-value pairs, where each key is associated with a specific value, similar to a real-life dictionary that maps each word to its definition.
Dictionaries in python are unordered, meaning that the order of items is not guaranteed. Additionally, dictionaries are mutable, which means that you can add, delete, and modify items within a dictionary. This makes dictionary an idea choice for many programming tasks.

## Creating a Dictionary.
In our example below, we will be creating a dictionary of countries and capitals, we can also create dictionaries of so many different types like an id, a name, and so on.

```
# dictionary = a collection of {key:value} pairs
#              ordered and changeable. No duplicates.

capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
print(capitals)
```
Results:

```
{'USA': 'Washington D.C', 'India': 'New Delhi', 'China': 'Beijing', 'Russia': 'Moscow'}
```
To see the attributes of a dictionary, we use the `dir()` function.

```
# dictionary = a collection of {key:value} pairs
#              ordered and changeable. No duplicates.

capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
print(dir(capitals))
```
Results:

```
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

```
For a detail description of all the attributes, you can use the `help()` function.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
print(dir(capitals))
print(help(capitals))
```
Results:

```
Help on dict object:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      True if the dictionary has the specified key, else False.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __ior__(self, value, /)
 |      Return self|=value.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(self, /)
 |      Return a reverse iterator over the dict keys.
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      D.__sizeof__() -> size of D in memory, in bytes
 |  
 |  clear(...)
 |      D.clear() -> None.  Remove all items from D.
 |  
 |  copy(...)
 |      D.copy() -> a shallow copy of D
 |  
 |  get(self, key, default=None, /)
 |      Return the value for key if key is in the dictionary, else default.
 |  
 |  items(...)
 |      D.items() -> a set-like object providing a view on D's items
 |  
 |  keys(...)
 |      D.keys() -> a set-like object providing a view on D's keys
 |  
 |  pop(...)
 |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 |      
 |      If the key is not found, return the default if given; otherwise,
 |      raise a KeyError.
 |  
 |  popitem(self, /)
 |      Remove and return a (key, value) pair as a 2-tuple.
 |      
 |      Pairs are returned in LIFO (last-in, first-out) order.
 |      Raises KeyError if the dict is empty.
 |  
 |  setdefault(self, key, default=None, /)
 |      Insert key with a value of default if key is not in the dictionary.
 |      
 |      Return the value for key if key is in the dictionary, else default.
 |  
 |  update(...)
 |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 |      If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 |      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 |      In either case, this is followed by: for k in F:  D[k] = F[k]
 |  
 |  values(...)
 |      D.values() -> an object providing a view on D's values
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  __class_getitem__(...) from builtins.type
 |      See PEP 585
 |  
 |  fromkeys(iterable, value=None, /) from builtins.type
 |      Create a new dictionary with keys from iterable and values set to value.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None
```
To get the a value from a dictionary, you use the `dictionaryname.get("value")` method, Let us see the example below.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
print(capitals.get("USA"))
```
and we have:

```
Washington D.C// as our output.
```
if the key you have imputed is not found, it will return `none`. For example, in the code below if we input Japan and Japan is not found.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
print(capitals.get("Japan"))
```
and we have our return value of `none`.

```
none
```
We can also test this using and `if` and `else` statements.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
if capitals.get("Japan"):
    print("That capital exists")
else:
    print("Capital does not exist")
```
and we have the output:

```
Capital does not exists
```
and if we replace with a value that is within our dictionary, then we see the message `That capital exists`.

We can also insert or update a key value pair in our dictionaries by using the `update({"value"})` function.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
capitals.update({"Germany": "Berlin"})
print(capitals)
```
and we now see that `Germany` has been inserted to our dictionary:

```
{'USA': 'Washington D.C', 'India': 'New Delhi', 'China': 'Beijing', 'Russia': 'Moscow', 'Germany': 'Berlin'}
```
Now let us update a key value pair using the `update({"value"})` function.
Let us update the capital of `USA` to be ` Detroit`. It is just an example for more understanding.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
capitals.update({"USA": "Detroit"})
print(capitals)
```
and now we have the capital updated.

```
{'USA': 'Detroit', 'India': 'New Delhi', 'China': 'Beijing', 'Russia': 'Moscow'}
```
To remove a value from a dictionary, you can use the `pop("value")` method, then pass in the value you would like to pop. For example, let us pop `China`.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
capitals.pop("China")
print(capitals)
```
Results:
```
{'USA': 'Washington D.C', 'India': 'New Delhi', 'Russia': 'Moscow'}
```
and now you can see that` China` no longer exist in our dictionary.
You can remove the latest key value within a dictionary by using the `popitem()` method. With `popitem()` method you don't need to pass in a key.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
capitals.popitem()
print(capitals)
```
Output:

```
{'USA': 'Washington D.C', 'India': 'New Delhi', 'China': 'Beijing'}
```
To clear all the elements of a dictionary, you can use the `clear() `method.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
capitals.clear()
print(capitals)
```
Output:

```
{}
```
To get all the keys within a dictionary without the values, there is a `keys()` method.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
keys = capitals.keys()
print(keys)
```
This will return all the keys within our dictionary.

```
dict_keys(['USA', 'India', 'China', 'Russia'])
```
Technically, keys are objects which resembles a list. Since they can be iterated, we can use a` for loop()`.

```

capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
keys = capitals.keys()
for key in capitals.keys():
    print(key)
```
and now we have:

```
USA
India
China
Russia
```
There is also the `values()` method, used to get all the values within a dictionary.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
values = capitals.values()
print(values)
```
Unlike the keys() method, it gives you all the values of a dictionary.

```
dict_values(['Washington D.C', 'New Delhi', 'Beijing', 'Moscow'])
```
The `values()` method also returns an object which resembles a list.
We can also print all the values within a dictionary by using the `for loop`.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
for value in capitals.values():
    print(value)
```
Here are all the values:

```
Washington D.C
New Delhi
Beijing
Moscow
```
We also have the `items()` method which is a little tricky but let us see how to understand it.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
items = capitals.items()
print(items)
```
The `items()` function returns dictionary object which resembles a 2D list of tuples. 

```
dict_items([('USA', 'Washington D.C'), ('India', 'New Delhi'), ('China', 'Beijing'), ('Russia', 'Moscow')])
```
This might be completed but let us see the use of items using a for loop.

```
capitals = {"USA": "Washington D.C",
            "India": "New Delhi",
             "China": "Beijing",
           "Russia": "Moscow"
            }
for key, value in capitals.items():
    print(f"{key}: {value}")
```
Let us see the results below.

```
USA: Washington D.C
India: New Delhi
China: Beijing
Russia: Moscow
```
So now you can see that you can print the keys and the values of a dictionary using the `items` method.
So that is a dictionary in Python, this might be more complex, but I just want to get you to understand the basics about dictionaries.

## Summary
A dictionary is a collection of keys and value pairs.
It is ordered and changeable and also does not accept duplicates.
Please do well to put your valuable comments in the comments section. Adios