Python Data Structures Part 3 Dictionaries

This notebook is about Python dictionaries.

A Python dict is a mutable set of key,value pairs.

  • lists
  • tuples
  • sets
  • dicts

part of #100DaysofCode Python Edition follow along at https://jcutrer.com/100daysofcode

Python Docs Reference: https://docs.python.org/3/tutorial/datastructures.html

Dictionaries

A pair of curly braces create an empty dictionary.

In [5]:
{}
Out[5]:
{}
In [10]:
type({})
Out[10]:
dict

If you remember from the last section {} are also used to create sets.

In [9]:
a = {'hello'}
type(a)
Out[9]:
set

This difference being that each item in a dict is a key value pair delimited with a :. Keys can be number as well.

In [15]:
a = {"Hello": "World", 1:2}
type(a)
print(a)
{'Hello': 'World', 1: 2}

len() will return the number of items in a dictionary

In [65]:
a = {'lat': 25.54241, 'long': -100.24362, 'altitude': 835}
len(a)
Out[65]:
3

Acces item of a dict by passing the disired key between square brackets.

In [26]:
print(a["lat"], a["long"])
25.54241 -100.24362
In [67]:
a.get("altitude") # equivelant to a["altitude"]
Out[67]:
835

When a non-existent key is accessed a KeyError exception is raised

In [17]:
a[0]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-17-6a1284577a36> in <module>
----> 1 a[0]

KeyError: 0

Add items to a dict

In [78]:
person = {"first": "John", "last": "Doe", "age": 23}
person["hair"] = "Brown"
person
Out[78]:
{'first': 'John', 'last': 'Doe', 'age': 23, 'hair': 'Brown'}

Update values by key

In [79]:
person = {"first": "John", "last": "Doe", "age": 23}
person["first"] = "Jane"
person
Out[79]:
{'first': 'Jane', 'last': 'Doe', 'age': 23}

remove items from a dict

In [63]:
person = {"first": "John", "last": "Doe", "age": 23}
del person["last"]
print(person)
{'first': 'John', 'age': 23}

tesing for a key in a dict

In [36]:
"first" in person
Out[36]:
True
In [38]:
"last" in person
Out[38]:
False

Extract all keys from a dict

In [46]:
person = {"first": "John", "last": "Doe", "age": 23}
keys = person.keys()
print(keys)
dict_keys(['first', 'last', 'age'])
In [50]:
type(keys)
Out[50]:
dict_keys

dict looping

looping over items in a dict

In [30]:
location = {'lat': 25.54241, 'long': -100.24362, 'altitude': 835}
for item in location:
    print(item)
lat
long
altitude

in this example we only get the values of each item

looping over a dict with access to key and value

In [40]:
location = {'lat': 25.54241, 'long': -100.24362, 'altitude': 835}
for key,item in location.items():
    print(key, "=", item)
lat = 25.54241
long = -100.24362
altitude = 835

comparing dictionaries

In [42]:
a = {"first":1, "avg": 2, "last": 3}
b = {"first":11, "avg": 22, "last": 33}

sorting & counting dictionaries

Alpha Sort items by key

In [23]:
inventory = {
    "apples": 34,
    "oranges": 54,
    "bananas": 66,
    "pairs": 12,
    "kiwis": 35
}
for key, value in sorted(inventory.items()):
    print (key + "\t\t", value)
apples		 34
bananas		 66
kiwis		 35
oranges		 54
pairs		 12

Sort items by len of value

In [29]:
inventory = {
    "apples": 34,
    "oranges": 54,
    "bananas": 66,
    "pairs": 12,
    "kiwis": 35
}

for key,value in sorted(inventory.items(), key=lambda x: x[1] ):
    print (key + "\t", value)

sorted(inventory, key=len)
pairs	 12
apples	 34
kiwis	 35
oranges	 54
bananas	 66
Out[29]:
['pairs', 'kiwis', 'apples', 'oranges', 'bananas']

Find the some of all dictionary values

In [35]:
inventory = {
    "apples": 34,
    "oranges": 54,
    "bananas": 66,
    "pairs": 12,
    "kiwis": 35
}

total_count = sum(inventory.values())
print("Total fruit count:", total_count)
Total fruit count: 201

OrderedDict

Python 3 introduced a new type of dictionary, an ordered dictionary preserves the order of keys as you would expect them to appear.

Historically, a dict does not preserve the order of keys. We can see this if we add additional keys.

In [83]:
days = {"monday": 8, "tuesday": 8, "wednesday": 8}
days["saturday"] = 8
days["sunday"] = 8
days["thursday"] = 8
days
Out[83]:
{'monday': 8,
 'tuesday': 8,
 'wednesday': 8,
 'saturday': 8,
 'sunday': 8,
 'thursday': 8}

Size of dict vs other data structures

In [92]:
somelist = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]
somelist.__sizeof__()
Out[92]:
112
In [103]:
somedict = dict(zip(range(0, len(somelist)), somelist))
somedict.__sizeof__()
Out[103]:
344
In [104]:
somedict = {0:"abc", 1: "def", 2: "ghi", 3: "jkl", 4: "mno", 5: "pqr", 6: "stu", 7: "vwx", 8: "yz"}
somedict.__sizeof__()
Out[104]:
344

as we can see dict uses 3x the memory of a list

This notebook is part of my #100DaysofCode Python Edition project.