-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #614 from realpython/python-dicts
Sample code for the article on dictionaries
- Loading branch information
Showing
17 changed files
with
300 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from collections import Counter | ||
|
||
print(Counter("mississippi")) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
inventory = dict.fromkeys(["apple", "orange", "banana", "mango"], 0) | ||
print(inventory) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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__) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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), | ||
} | ||
) |