<jupyter_start><jupyter_text>Dictionnary Author(s): amauryval<jupyter_code>from copy import deepcopy


input_dict = {
    "first_name": "John",
    "last_name": "Doe",
    "hobby": "sleeping",
    "age": 42
}<jupyter_output><empty_output><jupyter_text>1. Copy a dictionnnary into a new variable<jupyter_code>def dict_copy_with_copy_method(input_dict):
    return input_dict.copy()

def dict_copy_with_dict_cast(input_dict):
    return dict(input_dict)

def dict_copy_with_copy_library(input_dict):
    return copy(input_dict)

def dict_copy_with_deepcopy(input_dict):
    return deepcopy(input_dict)

%timeit dict_copy_with_copy_method(input_dict)
%timeit dict_copy_with_dict_cast(input_dict)
from copy import copy
%timeit dict_copy_with_copy_library(input_dict)
import ujson
%timeit dict_copy_with_deepcopy(input_dict)<jupyter_output>11.4 µs ± 553 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)<jupyter_text>2. Get an element on a dict<jupyter_code>def dict_element_with_key(input_dict):
    return input_dict["last_name"]

def dict_element_with_get_method(input_dict):
    return input_dict.get("last_name", None)
%timeit dict_element_with_key(input_dict)
%timeit dict_element_with_get_method(input_dict)<jupyter_output>252 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)<jupyter_text>3. Dict items() method<jupyter_code>def dict_loop_with_items_method(input_dict):
    return list(input_dict.items())

def dict_loop_with_keys_and_values_methods(input_dict):
    return list(zip(input_dict.keys(), input_dict.values()))
%timeit dict_loop_with_items_method(input_dict)
%timeit dict_loop_with_keys_and_values_methods(input_dict)<jupyter_output>1.19 µs ± 98.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
{'fraction_non_alphanumeric': 0.09572649572649573, 'fraction_numerical': 0.02621082621082621, 'mean_word_length': 7.401913875598086, 'pattern_counts': {'":': 4, '<': 14, '<?xml version=': 0, '>': 14, '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': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '559479', 'license': 'MIT', 'n_tokens_mistral': 691, 'n_tokens_neox': 645, 'n_words': 133, 'path': 'benchmarks/general/Dict_performance.ipynb', 'repo_name': 'geodatascience/geo_snippets', 'size': '1755'}