A Python dict
is a mutable set of key,value pairs.
part of #100DaysofCode Python Edition follow along at https://jcutrer.com/100daysofcode
Python Docs Reference: https://docs.python.org/3/tutorial/datastructures.html
A pair of curly braces create an empty dictionary.
{}
type({})
If you remember from the last section {}
are also used to create sets.
a = {'hello'}
type(a)
This difference being that each item in a dict
is a key value pair delimited with a :
. Keys can be number as well.
a = {"Hello": "World", 1:2}
type(a)
print(a)
len()
will return the number of items in a dictionary
a = {'lat': 25.54241, 'long': -100.24362, 'altitude': 835}
len(a)
Acces item of a dict
by passing the disired key between square brackets.
print(a["lat"], a["long"])
a.get("altitude") # equivelant to a["altitude"]
When a non-existent key is accessed a KeyError
exception is raised
a[0]
Add items to a dict
person = {"first": "John", "last": "Doe", "age": 23}
person["hair"] = "Brown"
person
Update values by key
person = {"first": "John", "last": "Doe", "age": 23}
person["first"] = "Jane"
person
remove items from a dict
person = {"first": "John", "last": "Doe", "age": 23}
del person["last"]
print(person)
tesing for a key in a dict
"first" in person
"last" in person
Extract all keys from a dict
person = {"first": "John", "last": "Doe", "age": 23}
keys = person.keys()
print(keys)
type(keys)
looping over items in a dict
location = {'lat': 25.54241, 'long': -100.24362, 'altitude': 835}
for item in location:
print(item)
in this example we only get the values of each item
looping over a dict
with access to key and value
location = {'lat': 25.54241, 'long': -100.24362, 'altitude': 835}
for key,item in location.items():
print(key, "=", item)
a = {"first":1, "avg": 2, "last": 3}
b = {"first":11, "avg": 22, "last": 33}
Alpha Sort items by key
inventory = {
"apples": 34,
"oranges": 54,
"bananas": 66,
"pairs": 12,
"kiwis": 35
}
for key, value in sorted(inventory.items()):
print (key + "\t\t", value)
Sort items by len of value
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)
Find the some of all dictionary values
inventory = {
"apples": 34,
"oranges": 54,
"bananas": 66,
"pairs": 12,
"kiwis": 35
}
total_count = sum(inventory.values())
print("Total fruit count:", total_count)
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.
days = {"monday": 8, "tuesday": 8, "wednesday": 8}
days["saturday"] = 8
days["sunday"] = 8
days["thursday"] = 8
days
dict
vs other data structures¶somelist = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]
somelist.__sizeof__()
somedict = dict(zip(range(0, len(somelist)), somelist))
somedict.__sizeof__()
somedict = {0:"abc", 1: "def", 2: "ghi", 3: "jkl", 4: "mno", 5: "pqr", 6: "stu", 7: "vwx", 8: "yz"}
somedict.__sizeof__()
as we can see dict
uses 3x the memory of a list
This notebook is part of my #100DaysofCode Python Edition project.