<jupyter_start><jupyter_text>Dicts<jupyter_code>import pandas as pd
from collections import defaultdict<jupyter_output><empty_output><jupyter_text>Converting data frame to dict<jupyter_code>df = pd.DataFrame({
    "Fare": [4, 10, 20],
    "Sex": ["m", "f", "m"],
    "Embarked": ["S", "C", "S"]
})

display(df)

print("Default:")
display(df.to_dict())

print("Records:")
display(df.to_dict("records"))<jupyter_output><empty_output><jupyter_text>Iterating<jupyter_code>dictionary = {
    "2020-04-01": 6,
    "2020-05-01": 8
}

for key, value in dictionary.items() :
    print(key + ": " + str(value))<jupyter_output>2020-04-01: 6
2020-05-01: 8<jupyter_text>Iterating by ascending value<jupyter_code>ages = {
    "matt": 35,
    "riker": 2,
    "mason": 5,
    "ava": 4
}

for name, age in sorted(ages.items(), key=lambda item: item[1]):
    print("{}: {}".format(name, age))<jupyter_output>riker: 2
ava: 4
mason: 5
matt: 35<jupyter_text>Deleting an item<jupyter_code>d = {"a": 5, "b": 6, "c": 7}
del d["a"]
print("New dict:", d)<jupyter_output>New dict: {'b': 6, 'c': 7}<jupyter_text>Or you can also return the deleted item:<jupyter_code>d = {"a": 5, "b": 6, "c": 7}
item = d.pop("a")
print("New dict:", d)
print("Deleted item:", item)<jupyter_output>New dict: {'b': 6, 'c': 7}
Deleted item: 5<jupyter_text>Number of keys<jupyter_code>d = {"a": 5, "b": 6, "c": 7}
len(d)<jupyter_output><empty_output><jupyter_text>Default Dict<jupyter_code>word_counts = defaultdict(int)
word_counts["machine"] = 10
print(word_counts)
print("machine:", word_counts["machine"])
print("learning:", word_counts["learning"])<jupyter_output>defaultdict(<class 'int'>, {'machine': 10})
machine: 10
learning: 0<jupyter_text>Creating a dict from a list  With no key values<jupyter_code>dict.fromkeys(["a", "b", "c"])<jupyter_output><empty_output><jupyter_text>With key values<jupyter_code>dict.fromkeys(["a", "b", "c"], 5)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.19875454073689672, 'fraction_numerical': 0.038401660612350806, 'mean_word_length': 6.805668016194332, 'pattern_counts': {'":': 19, '<': 37, '<?xml version=': 0, '>': 37, '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': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '497799', 'license': 'MIT', 'n_tokens_mistral': 867, 'n_tokens_neox': 793, 'n_words': 161, 'path': 'Dicts.ipynb', 'repo_name': 'dbl007/python-cheat-sheet', 'size': '1927'}