Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample code for the article on dictionaries #614

Merged
merged 5 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python-dicts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Dictionaries in Python

This folder provides the code examples for the Real Python tutorial [Dictionaries in Python](https://realpython.com/python-dicts/).
62 changes: 62 additions & 0 deletions python-dicts/configs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
config = {
"color": "green",
"width": 42,
"height": 100,
"font": "Courier",
}

# Access a value through its key
print(config["color"])

# Update a value
config["font"] = "Helvetica"
print(config)

config = {
"color": "green",
"width": 42,
"height": 100,
"font": "Courier",
}
user_config = {
"path": "/home",
"color": "red",
"font": "Arial",
"position": (200, 100),
}
config.update(user_config)
print(config)
config.update([("width", 200), ("api_key", 1234)])
print(config)
config.update(color="yellow", script="__main__.py")
print(config)

default_config = {
"color": "green",
"width": 42,
"height": 100,
"font": "Courier",
}
user_config = {
"path": "/home",
"color": "red",
"font": "Arial",
"position": (200, 100),
}
config = default_config | user_config
print(config)

config = {
"color": "green",
"width": 42,
"height": 100,
"font": "Courier",
}
user_config = {
"path": "/home",
"color": "red",
"font": "Arial",
"position": (200, 100),
}
config |= user_config
print(config)
3 changes: 3 additions & 0 deletions python-dicts/counter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from collections import Counter

print(Counter("mississippi"))
4 changes: 4 additions & 0 deletions python-dicts/dict_zip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
cities = ["Colorado", "Chicago", "Boston", "Minnesota", "Milwaukee", "Seattle"]
teams = ["Rockies", "White Sox", "Red Sox", "Twins", "Brewers", "Mariners"]

print(dict(zip(cities, teams)))
15 changes: 15 additions & 0 deletions python-dicts/employees.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from collections import defaultdict

employees = [
("Sales", "John"),
("Sales", "Martin"),
("Accounting", "Kate"),
("Marketing", "Elizabeth"),
("Marketing", "Linda"),
]

departments = defaultdict(list)
for department, employee in employees:
departments[department].append(employee)

print(departments)
4 changes: 4 additions & 0 deletions python-dicts/equality.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
print([1, 2, 3] == [3, 2, 1])
print({1: 1, 2: 2, 3: 3} == {3: 3, 2: 2, 1: 1})
print([1, 2, 3] != [3, 2, 1])
print({1: 1, 2: 2, 3: 3} != {3: 3, 2: 2, 1: 1})
2 changes: 2 additions & 0 deletions python-dicts/from_keys.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
inventory = dict.fromkeys(["apple", "orange", "banana", "mango"], 0)
print(inventory)
12 changes: 12 additions & 0 deletions python-dicts/inventory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
inventory = {"apple": 100, "orange": 80, "banana": 100}
inventory.get("apple")

print(inventory.get("mango"))

print(inventory.get("mango", 0))

print(inventory.values())

print(inventory.keys())

print(inventory.items())
32 changes: 32 additions & 0 deletions python-dicts/iteration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
students = {
"Alice": 89.5,
"Bob": 76.0,
"Charlie": 92.3,
"Diana": 84.7,
"Ethan": 88.9,
"Fiona": 95.6,
"George": 73.4,
"Hannah": 81.2,
}
for student in students:
print(student)

for student in students.keys():
print(student)

for student in students:
print(student, "->", students[student])

MLB_teams = {
"Colorado": "Rockies",
"Chicago": "White Sox",
"Boston": "Red Sox",
"Minnesota": "Twins",
"Milwaukee": "Brewers",
"Seattle": "Mariners",
}
for team in MLB_teams.values():
print(team)

for city, team in MLB_teams.items():
print(city, "->", team)
32 changes: 32 additions & 0 deletions python-dicts/membership.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import timeit

MLB_teams = {
"Colorado": "Rockies",
"Chicago": "White Sox",
"Boston": "Red Sox",
"Minnesota": "Twins",
"Milwaukee": "Brewers",
"Seattle": "Mariners",
}

# Run timeit to compare the membership test
time_in_dict = timeit.timeit(
'"Milwaukee" in MLB_teams', globals=globals(), number=1000000
)
time_in_keys = timeit.timeit(
'"Milwaukee" in MLB_teams.keys()', globals=globals(), number=1000000
)
time_not_in_dict = timeit.timeit(
'"Indianapolis" in MLB_teams', globals=globals(), number=1000000
)
time_not_in_keys = timeit.timeit(
'"Indianapolis" in MLB_teams.keys()', globals=globals(), number=1000000
)

print(
f"{time_in_dict = } seconds",
f"{time_in_keys = } seconds",
f"{time_not_in_dict = } seconds",
f"{time_not_in_keys = } seconds",
sep="\n",
)
33 changes: 33 additions & 0 deletions python-dicts/mlb_teams.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
MLB_teams = {
"Colorado": "Rockies",
# "Chicago": "White Sox",
"Chicago": "Chicago Cubs",
"Boston": "Red Sox",
"Minnesota": "Twins",
"Milwaukee": "Brewers",
"Seattle": "Mariners",
}
print(MLB_teams)

MLB_teams = dict(
[
("Colorado", "Rockies"),
("Chicago", "White Sox"),
("Boston", "Red Sox"),
("Minnesota", "Twins"),
("Milwaukee", "Brewers"),
("Seattle", "Mariners"),
]
)
print(MLB_teams)


print("Milwaukee" in MLB_teams)
print("Indianapolis" in MLB_teams)
print("Indianapolis" not in MLB_teams)
print("Milwaukee" in MLB_teams.keys())
print("Indianapolis" in MLB_teams.keys())
print("Indianapolis" not in MLB_teams.keys())

print(("Boston", "Red Sox") in MLB_teams.items())
print(("Boston", "Red Sox") not in MLB_teams.items())
6 changes: 6 additions & 0 deletions python-dicts/number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class Number:
def __init__(self, value):
self.value = value


print(Number(42).__dict__)
21 changes: 21 additions & 0 deletions python-dicts/person.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
person = {
"first_name": "John",
"last_name": "Doe",
"age": 35,
"spouse": "Jane",
"children": ["Ralph", "Betty", "Bob"],
"pets": {"dog": "Frieda", "cat": "Sox"},
}

print(person["children"][0])
print(person["children"][2])
print(person["pets"]["dog"])

person = {}
person["first_name"] = "John"
person["last_name"] = "Doe"
person["age"] = 35
person["spouse"] = "Jane"
person["children"] = ["Ralph", "Betty", "Bob"]
person["pets"] = {"dog": "Frieda", "cat": "Sox"}
print(person)
35 changes: 35 additions & 0 deletions python-dicts/sorted_dict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class SortableDict(dict):
def sort_by_keys(self, reverse=False):
sorted_items = sorted(
self.items(), key=lambda item: item[0], reverse=reverse
)
self.clear()
self.update(sorted_items)

def sort_by_values(self, reverse=False):
sorted_items = sorted(
self.items(), key=lambda item: item[1], reverse=reverse
)
self.clear()
self.update(sorted_items)


students = SortableDict(
{
"Alice": 89.5,
"Bob": 76.0,
"Charlie": 92.3,
"Diana": 84.7,
"Ethan": 88.9,
"Fiona": 95.6,
"George": 73.4,
"Hannah": 81.2,
}
)

print(id(students))
students.sort_by_keys()
print(students)
students.sort_by_values(reverse=True)
print(students)
print(id(students))
10 changes: 10 additions & 0 deletions python-dicts/squares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
squares = {}

for integer in range(1, 10):
squares[integer] = integer**2

print(squares)

squares = {integer: integer**2 for integer in range(1, 10)}

print(squares)
12 changes: 12 additions & 0 deletions python-dicts/students.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
students = {
"Alice": 89.5,
"Bob": 76.0,
"Charlie": 92.3,
"Diana": 84.7,
"Ethan": 88.9,
"Fiona": 95.6,
"George": 73.4,
"Hannah": 81.2,
}
print(dict(sorted(students.items(), key=lambda item: item[1])))
print(dict(sorted(students.items(), key=lambda item: item[1], reverse=True)))
14 changes: 14 additions & 0 deletions python-dicts/values.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Point:
def __init__(self, x, y):
self.x = x
self.y = y


print(
{
"colors": ["red", "green", "blue"],
"plugins": {"py_code", "dev_sugar", "fasting_py"},
"timeout": 3,
"position": Point(42, 21),
}
)
Loading