<jupyter_start><jupyter_text>Dictionaries<jupyter_code># create a dictionary

person = {
    "name": "Mike",
    "age": 42
}

print(person)
# access, update and remove items

person = {
    "name": "Mike",
    "age": 42
}

# Output: Mike
print(person["name"]) # will return key error if key doesn't exist
print(person.get("name")) # will return None if key doesn't exist

# Output: default
print(person.get("last_name", "default"))

# update with iterable
person.update(name="John", age=43)
print(person)

# update with dictionary
person.update({"name": "Bob"})
print(person)

# update by assignment
person["location"] = "Texas"
print(person)

# remove key value pair,
# the return from pop is the value not the key value pair tuple
value = person.pop("location")
print(person)
print(value)

# remove all items
person.clear()

# delete dictionary
del person
# dictionary keys can be of string, number or tuple

person = {
    "name": "Mike",
    42: "age",
    ("Ken", "Jane"): "parents"
}

print(person)
# unpacking

person = {
    "name": "Mike",
    "age": 42
}

# Output: name age
a, b = person
print(a, b)

# Output: ('name', 'Mike') ('age', 42)
a, b = person.items()
print(a, b)

# unpacking (deep)

favorite_snacks = {
    'salty': ('pretzels', 100),
    'sweet': ('cookies', 180),
    'veggie': ('carrots', 20),
}
((type1, (name1, cals1)),
 (type2, (name2, cals2)),
 (type3, (name3, cals3))) = favorite_snacks.items()

print(f'Favorite {type1} is {name1} with {cals1} calories')
print(f'Favorite {type2} is {name2} with {cals2} calories')
print(f'Favorite {type3} is {name3} with {cals3} calories')<jupyter_output>Favorite salty is pretzels with 100 calories
Favorite sweet is cookies with 180 calories
Favorite veggie is carrots with 20 calories
{'fraction_non_alphanumeric': 0.15849486887115166, 'fraction_numerical': 0.026225769669327253, 'mean_word_length': 4.679611650485437, 'pattern_counts': {'":': 8, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '355358', 'license': 'MIT', 'n_tokens_mistral': 663, 'n_tokens_neox': 615, 'n_words': 195, 'path': 'dictionary.ipynb', 'repo_name': 'babeal/python-edu', 'size': '1754'}