Post

Dictionaries - Storing Data Like a Database, Right In Python...

While the title of this blog implies that a dictionary list in Python is a database, it's not. How it works, however, is very close to that of a database. Each entry stored has its own 'Key':'Value'. The key to each value is used to perform functions, replacing the need for indices. Here's what I've learnt about dictionaries on Day 8.

Dictionaries - Storing Data Like a Database, Right In Python...

Up to this point, I’ve explored Lists, Tuples, and Sets while revisiting the 30 Days of Python course by Asabeneh1. The next step is to focus on Dictionaries in Python and unveil how flexible yet durable they are.

Unlike sets, Dictionaries can be described as being miniature databases within a program. The only quirk here is that you can refer to each value within it using the key.

If we recall, for Sets, Tuples, and Lists we use indices to access elements inside. The advantage of using dictionaries comes to how we store the data and what we can do with them.

Think about how easy it would be to refer to a piece of data within a collection data set using terms rather than indices. You would know what data you want from your ‘database’ and bring that back.

To deepen my explanation, Dictionaries use 'Key':'Value' pairs to store information. 'fname':'Sheikh' is the format you would use to create elements inside a dictionary.

Think of the key value replacing the indices.

Each key must be unique, and the data inside a key can be any data type, including other list types. I did want to spend some time introducing this topic, as it did pique my interest when I discovered it on my first pass.


Creating a Dictionary

To create a dictionary in Python, we use {} and assign them to a variable.

1
2
3
4
5
empty_dict = {}
empty_dict_b = dict()
lst = {"fname":"Sheikh", "sname":"Hussain"} # Adding items using key:value pairs.

print(dct['fname']) # Sheikh

Here is a more detailed example of what a dictionary could look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
person = {
  'first_name':'Sheikh', # String
  'last_name':'Hussain',
  'age':250, # Integer
  'country':'UK',
  'is_marred':False, # Boolean
  'skills':['Python', 'HTML', 'CSS'], # List
  'address':{
     'street':'Space street',
     'zipcode':'02210'
 } # Set
}

print(len(person)) # 7
# Only counts the keys to calculate the length

Taken from the course

Accessing Items In a Dictionary

As mentioned in the intro, we’ll now be able to access items using their key value instead of a numeric value for the index or indices.

1
2
3
4
lst = {"fname":"Sheikh", "age":500}

print(lst["fname"]) # Sheikh
print(type(lst['age'])) # integer

This should start to build the picture when it comes to what we could do with dictionaries in Python, to make things more intriguing…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
person = {
  'first_name':'Sheikh',
  'last_name':'Hussain',
  'age':250,
  'country':'UK',
  'is_marred':False,
  'skills':['Python', 'HTML', 'CSS'],
  'address':{
     'street':'Space street',
     'zipcode':'02210'
 }
 }

print(person['address']['street']) # Space street

This example, should help us understand how we are able to access lists and their contents that are placed inside.

This is similar to what we’ve learnt earlier for lists.

What helped me figure my way around this is to think that we are still dealing with sequencing, and so we’ll still have access to those operations.

When writing in any programming language, the idea that is that we would create a program that is always running. The purpose behind this is so that there isn’t a point in which the program comes to a halt.

We try and avoid this as much as possible by writing code that would save data, externally or internally, by using something similar to CRUD operations.

That’s what I’ve gathered so far about collection data types.

One method we can use with Dictionaries is that we can use the get() function instead, which will return None if the item doesn’t exist.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
person = {
  'first_name':'Sheikh',
  'last_name':'Hussain',
  'age':250,
  'country':'UK',
  'is_marred':False,
  'skills':['Python', 'HTML', 'CSS'],
  'address':{
     'street':'Space street',
     'zipcode':'02210'
 }
 }

print(person.get("Key5")) # None
print(person.get('first_name')) # Sheikh

Adding Items To a Dictionary

Adding items is different to other list types, however, not complicated.

You just need to specify the new key and object when storing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
person = {
  'first_name':'Sheikh',
  'last_name':'Hussain',
  'age':250,
  'country':'UK',
  'is_marred':False,
  'skills':['Python', 'HTML', 'CSS'],
  'address':{
     'street':'Space street',
     'zipcode':'02210'
 }
 }

person['age'] = 150 # Adding as usual to a dictionary
person['skills'].append("Git") # Using the correct syntax for list to add

Modifying Items In a Dictionary

For me, there are still some nuances that I would like to learn when it comes to modifying items like, how would we modify items that exist within a list inside of a key?

For now, however, the method used to modify the contents of an existing key would be very similar to how we add items; we would just reference the old key.

1
2
3
4
5
6
7
8
dct = {'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}

dct['key1'] = "New Value"

Membership Operators

Again, very similar to what we have gone over in the past posts, we just use the in operator.

1
2
3
4
5
6
7
8
9
dct = {'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}

print('key1' in dct) # True
# We can also check the values instead
print('value1' in dct.values()) # True

Removing Items From a Dictionary

1
2
3
4
5
6
7
8
9
dct = {'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}

dct.pop('key1') # Will remove both key and value
dct.popitem() # Will remove the last item in the dictionary
del dct['key1'] # Deletes the key and value

Changing Dictionaries

Changing a dictionary to another collection data type will often result in having the key and value being stored as separate lists.

1
2
3
4
5
6
7
8
9
10
11
12
13
dct = {'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}

print(dct.items()) # This prints them all in tuples

tup = tuple(dct.items()) # creates a tuple and stores each key value as a tuple.
st = set(dct.items())
lst = list(dct.items())

# i.e - ((key:value), (key:value))

Clearing and Deleting a Dictionary

1
2
3
4
5
6
7
8
9
10
dct = {'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}

dct.clear()
print(dct) # {}

del dct

Copying a Dictionary

1
2
3
4
5
6
7
dct = {'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}

new_dct = dct.copy()

Produce a List of All Keys or Values

1
2
3
4
5
6
7
8
dct = {'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}

keys = dct.keys() # Brings back all keys
values = dct.values() # Brings back all values

Wrapping up

This topic, for me, has been a real insight into what we could do with Python. I found this useful when it came to creating programs like a Task manager2 where it is required that we save information to a local file and retrieve/modify, when needed.

I would still like to use some of these functions a little more before I could say that I’m comfortable with them. I think on the possibilities with this feature in Python which indicates that even a simple program, could possess the abilities of performing very complex algorithms.

Footnote:

  1. 30 Days of Python - Asabeneh ↩︎

  2. Python Task Manager Please don’t download without anti-virus software’s ↩︎

This post is licensed under CC BY 4.0 by the author.