FANDOM


This page is basically just a run down of how to use dictionaries in Python, and some handy use cases.


What is it?Edit

A dictionary is an unordered, changeable, and indexed collection of key value pairs.

You can create a basic dictionary like this:

newDict = {"Name": "Renee", "Age": 27, "Country": "Australia"}

The keys in the above dictionary newDict are "Name", "Age", and "Country".

The values are "Renee", 27, and "Australia".


Accessing ItemsEdit

To access the VALUE in a dictionary you can say:

name = newDict["Name"]


Change ValuesEdit

You can change the value of an item in the dictionary by doing the following:

newDict["Age"] = 28


Iterating Through a DictionaryEdit

When looping through a dictionary the return value are the KEYS of the dictionary, but there are methods to return the VALUES as well.

For example, we can print all the KEY names:

for each in newDict:
    print(each)

# This will return the following :
Name
Age
Country


We can print the VALUES:

for each in newDict:
    print(newDict[each])

# This will return the following:
Renee
27
Australia


We can loop through both KEYS AND VALUES:

for key, value in newDict.items():
    print(key, value)

# This will return the following:
Name Renee
Age 27
Country Australia


Checking If a Key ExistsEdit

We can check if a specific KEY is in the dictionary using the in keyword:

if "Age" in newDict:
   print("Yes, Age is a key in this dict...")


Checking If a Value ExistsEdit

We can check if a specific VALUE is in the dictionary using the values() function:

if "Australia" in newDict.values():
    print("Australia was found!")


Dictionary LengthEdit

To determine how many key-value pairs a dictionary has we use the len() method:

print(len(newDict))


Adding ItemsEdit

To add an item we use a new index key and assign a new value to it:

newDict["Eye Colour"] = "Hazel"


Removing ItemsEdit

There are several ways of doing this.

The first way is to use the pop() method, which removes the item with the specific key name:

newDict.pop("Country")

We can also do this by using the  del keyword:

del newDict["Country"]


Nested DictionaryEdit

A nested dicitonary is a dictionary INSIDE a dictionary. For example:

nestedDict = {'dict01': {'key01': 'value01'},
              'dict02': {'key02': 'value02'}
             }

So the above example has two dictionaries inside a dictionary. With each of the inner dictionaries having one key-value pair.


Accessing Elements Edit

To access the elements of a nested dictionary we can do the following:

print(nestedDict['dict01']['key01'])

# This will return:
value01


Adding or Change an ElementEdit

Lets say we wanted to add another inner dictionary called 'dict03' with it's own key value pair. We could do the following:

nestedDict['dict03'] = {}
nestedDict['dict03']['key03'] = 'value03'

This would leave you with a nestedDict that looks like this:

nestedDict = {'dict01': {'key01': 'value01'},
              'dict02': {'key02': 'value02'},
              'dict03': {'key03': 'value03'}
             }

or you could simply write:

nestedDict['dict03'] = {'key03': 'value03'}


Iterating ThroughEdit

Using nested for-loops we can access the different levels of our dictionary:

for upperKey, upperValue in nestedDict.items():
    for innerKey, innverValue in upperValue.items():
        print(innerKey, innerValue)

# This will return the following:
key01 value01
key02 value02
key03 value03


Dictionary MethodsEdit

Python has a bunch of built-in methods that you can use on your dictionaries:

Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing a tuple of each key-value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

OrderedDictEdit

An OrderedDict is a dictionary subclass that remembers the order that the keys were first inserted.

The difference between an OrderedDict() and a regular dict() is that an OrderedDict preserves the order in which the keys were inserted. Whereas a regular dict() does not track the insertion order so iteraring through a dict() gives the values in an arbitrary order.

To create an OrderedDict you can simply write:

from collections import OrderedDict

od = OrderedDict()
od["one"] = 1
od["two"] = 2
od["three"] = 3
od["four"] = 4


ReferencesEdit

Python Dictionaries - w3schools.com

Python Nested Dictionaries - Programiz

OrderedDict in Python - GeeksforGeeks

Community content is available under CC-BY-SA unless otherwise noted.