Skip to content

Instantly share code, notes, and snippets.

@raeq
raeq / dict_16_dynamic.py
Created August 6, 2020 06:09
Remove items from a dictionary with matching value
def remove_even_items(the_dict: dict):
# collect the keys of all the items to remove
delete_these = set(k for k, v in the_dict.items() if v % 2 == 0)
for delete_this in delete_these:
del the_dict[delete_this]
return the_dict
@raeq
raeq / dict_15_json.py
Created August 6, 2020 05:23
Complex dictionary to JSON
import json
from datetime import datetime
class PythonObjectEncoder(json.JSONEncoder):
def default(self, an_object_value):
if isinstance(an_object_value, str):
return an_object_value
@raeq
raeq / dict_15_json.py
Created August 6, 2020 05:07
Complex dictionaries to JSON
from datetime import datetime
import json
class PythonObjectEncoder(json.JSONEncoder):
"""PythonObjectEncoder.
"""
def default(self, an_object_value):
"""default.
@raeq
raeq / dict_13_invert.py
Created August 5, 2020 17:22
Invert dictionary
def invert_dictionary(input:dict)->dict:
return {v: k for k, v in dict1.items()}
dict1 = {"a": 1, "b": 2, "c": 3}
assert invert_dictionary(dict1) == {1: "a", 2: "b", 3: "c"}
@raeq
raeq / dict_12_deepcopy.py
Created August 5, 2020 13:15
Dictionary deepcopy
import copy
original = {}
original["object1"] = dict({"a": {"b": [1, 2, 3]}})
dict_shallow = original.copy()
dict_deep = copy.deepcopy(original)
# change the mutable object in original and dict_shallow
original["object1"]["a"]["b"] = [3, 4, 5]
@raeq
raeq / dict_11_removeitem.py
Created August 3, 2020 13:07
Delete an item.
digits: dict = {i: chr(+i) for i in range(48, 58, 1)}
key = 50
try:
val = digits.pop(key)
except KeyError:
print (f"The item with key {key} did not exist.")
else:
print(f"Deleted item with key {key} with value {val}.")
@raeq
raeq / dict_10_fromcsv.py
Created August 3, 2020 12:34
Use the CSV module
from collections import defaultdict as dd
import csv
import requests
url: str = "https://data.london.gov.uk/download/london-borough-profiles/c1693b82-68b1-44ee-beb2-3decf17dc1f8/london-borough-profiles.csv "
boroughs = (requests.get(url).text).split("\n")
reader = csv.DictReader(boroughs, dialect="excel")
dict1 = dd(dict)
@raeq
raeq / dict_10_fromcsv.py
Created August 3, 2020 12:32
Use the CSV package
from collections import defaultdict as dd
import requests
import csv
from pprint import pprint
url: str = "https://data.london.gov.uk/download/london-borough-profiles/c1693b82-68b1-44ee-beb2-3decf17dc1f8/london" "-borough-profiles.csv "
boroughs = (requests.get(url).text).split("\n")
reader = csv.DictReader(boroughs, dialect="excel")
dict1 = dd(dict)
@raeq
raeq / dict_09_tuples.py
Created August 3, 2020 09:54
Tuples to Dictionary
from collections import defaultdict as dd
s = [("John", "Male", 25), ("Fred", "Female", 48), ("Sam", "Female", 41),
("Jane", "Female", 25)]
dict1 = dd(dict)
for name, gender, age in s:
dict1[name]["age"] = age
dict1[name]["gender"] = gender
@raeq
raeq / dict_08_default.py
Created August 3, 2020 09:44
Using a defaultdict
from collections import defaultdict as dd
s = [("John", "Male"), ("John", "48"), ("John", "Married"), ("Jane", "Female"),
("Jane", "25")]
dict1: dict = dd(list)
for k, v in s:
dict1[k].append(v)