.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/basics/dictionaries.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_basics_dictionaries.py: ================ 1.6 dictionary ================ This lesson describes a special data structure of python called ``dictionary``. .. GENERATED FROM PYTHON SOURCE LINES 10-16 Intro ======== Dictionaries are data containers that store the data as key, value pairs. Each value in a dictionary is associated with a key, and threfore every key must have a value associated with it. Therefore, dictionaries are also sometimes known as associative arrays. .. GENERATED FROM PYTHON SOURCE LINES 18-20 We can define a dictionary using curly brackets "{}". Each key and value pair must be separated by a comma "," while a colon ":" is used to separate a key from its vlaue. .. GENERATED FROM PYTHON SOURCE LINES 20-28 .. code-block:: default man = {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1979, "0": 0 } .. GENERATED FROM PYTHON SOURCE LINES 29-31 We can verify that whether a python object is dictionary or not by checking its ``type``. A variable which is a dictionary has a ``dict`` type. .. GENERATED FROM PYTHON SOURCE LINES 31-34 .. code-block:: default print(type(man)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 35-37 We can access data from a dictionary by making use of slice operator ``[]``. .. GENERATED FROM PYTHON SOURCE LINES 39-42 .. code-block:: default print(man["name"]) .. rst-class:: sphx-glr-script-out .. code-block:: none Baqir -al- Sadr .. GENERATED FROM PYTHON SOURCE LINES 43-45 Inside the square bracket, we can write any ``key`` which is present in the dicionary and we will get the value associated with it. .. GENERATED FROM PYTHON SOURCE LINES 45-47 .. code-block:: default print(man["citizenship"]) .. rst-class:: sphx-glr-script-out .. code-block:: none Iraq .. GENERATED FROM PYTHON SOURCE LINES 48-50 If we try to a access value whose corresponding key does not exist in the dictionary, we will get ``KeyError``. .. GENERATED FROM PYTHON SOURCE LINES 50-54 .. code-block:: default # uncomment following line # man["city"] # -> KeyError .. GENERATED FROM PYTHON SOURCE LINES 55-58 The error suggests that the dictionary ``man`` does not have a key named `city`. The key must be the same object as when it was defined. We can not use indexing for keys such as .. GENERATED FROM PYTHON SOURCE LINES 58-62 .. code-block:: default # uncomment following line # man[0] # KeyError .. GENERATED FROM PYTHON SOURCE LINES 63-65 The ``man`` key does have a key with the name '0' but this is string type and we provide 0 as integer and threfore we got KeyError. .. GENERATED FROM PYTHON SOURCE LINES 67-68 We can add a new key, value pair in an existing dictionary as following .. GENERATED FROM PYTHON SOURCE LINES 70-75 .. code-block:: default man["city"] = "Baghdad" print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1979, '0': 0, 'city': 'Baghdad'} .. GENERATED FROM PYTHON SOURCE LINES 76-77 Thus we can start with an empty dictionary and populate it later on .. GENERATED FROM PYTHON SOURCE LINES 80-85 .. code-block:: default man = {} print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {} .. GENERATED FROM PYTHON SOURCE LINES 86-95 .. code-block:: default man["city"] = "Baghdad" man["name"] = "Baqir -al- Sadr" man["born"] = 1935 man["citizenship"] = "Iraq" man["died"] = 1979 print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {'city': 'Baghdad', 'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1979} .. GENERATED FROM PYTHON SOURCE LINES 96-97 The values to different keys in a dictionary can be same. .. GENERATED FROM PYTHON SOURCE LINES 99-105 .. code-block:: default man["birth_place"] = "Baghdad" man["death_place"] = "Baghdad" print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {'city': 'Baghdad', 'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1979, 'birth_place': 'Baghdad', 'death_place': 'Baghdad'} .. GENERATED FROM PYTHON SOURCE LINES 106-108 But we can not have a dictionary with two or more same keys. If we add a new key with same name, the previous key, value will be replaced. .. GENERATED FROM PYTHON SOURCE LINES 110-114 .. code-block:: default man["died"] = 1980 print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {'city': 'Baghdad', 'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1980, 'birth_place': 'Baghdad', 'death_place': 'Baghdad'} .. GENERATED FROM PYTHON SOURCE LINES 115-118 `type` of keys and values ========================== The values in a dictionary can be of any type. .. GENERATED FROM PYTHON SOURCE LINES 120-129 .. code-block:: default colonies = {"british": ["India", "Australia"], "french": "Libya", "polish": 0, "german": 3.5, # most of their colonies are split and joined into new countires. "cuba": None} print(colonies) .. rst-class:: sphx-glr-script-out .. code-block:: none {'british': ['India', 'Australia'], 'french': 'Libya', 'polish': 0, 'german': 3.5, 'cuba': None} .. GENERATED FROM PYTHON SOURCE LINES 130-131 But the keys of a dictionary must be immutable. .. GENERATED FROM PYTHON SOURCE LINES 133-139 .. code-block:: default persons = {1: "Adam", "Two": "Eva"} print(persons) .. rst-class:: sphx-glr-script-out .. code-block:: none {1: 'Adam', 'Two': 'Eva'} .. GENERATED FROM PYTHON SOURCE LINES 140-144 .. code-block:: default # uncomment following line # persons[[0, 1]] = ["Adam", "Eva"] # TypeError .. GENERATED FROM PYTHON SOURCE LINES 145-146 Making a real practical dictionary .. GENERATED FROM PYTHON SOURCE LINES 148-154 .. code-block:: default ur_per = {"admi": "mard", "aurat": "zan", "bacha": "tefl", "paighambar": "paighambar"} per_ar = {"mard": "rojol", "zan": "nissa", "tefl": "tefl", "paighambar": "paighambar"} print("The Arabic word for aurat is: " + per_ar[ur_per["aurat"]]) .. rst-class:: sphx-glr-script-out .. code-block:: none The Arabic word for aurat is: nissa .. GENERATED FROM PYTHON SOURCE LINES 155-160 ``keys`` and ``values`` methods ================================== We can get all the keys of a dictionary using ``.keys()`` method on dictionary. The dot "." here signifies that the ``keys()`` function comes from dictionary. This means any variable which is a dictionary, will have .keys() function in it. .. GENERATED FROM PYTHON SOURCE LINES 162-169 .. code-block:: default books = {"AlSadr": ["Our Philosophy", "Our Economy"], "Mutahri": ["Divine Justice", "Man and Destiny"] } keys = books.keys() print(keys) .. rst-class:: sphx-glr-script-out .. code-block:: none dict_keys(['AlSadr', 'Mutahri']) .. GENERATED FROM PYTHON SOURCE LINES 170-171 Algthouh the printing keys look like ``list`` but in reality their time is not ``list``. .. GENERATED FROM PYTHON SOURCE LINES 171-173 .. code-block:: default print(type(keys)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 174-175 We can convert keys of a dictionary into ``list`` type as follows .. GENERATED FROM PYTHON SOURCE LINES 175-179 .. code-block:: default keys_as_list = list(keys) print(type(keys_as_list)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 180-183 .. code-block:: default print(keys_as_list) .. rst-class:: sphx-glr-script-out .. code-block:: none ['AlSadr', 'Mutahri'] .. GENERATED FROM PYTHON SOURCE LINES 184-185 Similarly we can convert values of a dictionary into ``list`` type as follows .. GENERATED FROM PYTHON SOURCE LINES 185-194 .. code-block:: default values = books.values() values = list(values) print(values) print(type(values)) .. rst-class:: sphx-glr-script-out .. code-block:: none [['Our Philosophy', 'Our Economy'], ['Divine Justice', 'Man and Destiny']] .. GENERATED FROM PYTHON SOURCE LINES 195-206 **Question:** Consider the following two dictionries: .. code-block:: python a = {"Ali": 661, "Hassan": 670, "Hussain": 680, "Abid": 712, "Baqir": 733, "Jafar": 765} b = {"Musa": 799, "Raza": 818, "Taqi": 835, "Naqi": 868, "Hassan": 874, "Hussain": None} Write the code which will return a single list of values from both dictionaries i.e. the code should return ``[661, 670, 680, 712, 733, 765, 799, 818, 835, 868, 874, None]``. .. GENERATED FROM PYTHON SOURCE LINES 208-209 The function ``items()`` when applied on a dictionay, returns both keys and values. .. GENERATED FROM PYTHON SOURCE LINES 209-213 .. code-block:: default items = books.items() print(items) .. rst-class:: sphx-glr-script-out .. code-block:: none dict_items([('AlSadr', ['Our Philosophy', 'Our Economy']), ('Mutahri', ['Divine Justice', 'Man and Destiny'])]) .. GENERATED FROM PYTHON SOURCE LINES 214-216 .. code-block:: default print(type(items)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 217-222 .. code-block:: default books_as_list = list(books.items()) print(books_as_list) .. rst-class:: sphx-glr-script-out .. code-block:: none [('AlSadr', ['Our Philosophy', 'Our Economy']), ('Mutahri', ['Divine Justice', 'Man and Destiny'])] .. GENERATED FROM PYTHON SOURCE LINES 223-224 Each member of ``books_as_list`` is a tuple of two elements (keys and values). .. GENERATED FROM PYTHON SOURCE LINES 224-227 .. code-block:: default print(type(books_as_list[0])) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 228-231 .. code-block:: default print(books_as_list[0]) .. rst-class:: sphx-glr-script-out .. code-block:: none ('AlSadr', ['Our Philosophy', 'Our Economy']) .. GENERATED FROM PYTHON SOURCE LINES 232-237 dictionaries from lists ======================= If we have two lists and we want to convert them into a dictionary, in such a way that the first list becomes keys and the second list becomes values, we can do this as follows .. GENERATED FROM PYTHON SOURCE LINES 237-243 .. code-block:: default provinces_capitals_dict = dict( list(zip(["Balochistan", "Sindh", "KPK", "Punjab"], ["Quetta", "Karachi", "Peshawar", "Lahore"]))) print(provinces_capitals_dict) .. rst-class:: sphx-glr-script-out .. code-block:: none {'Balochistan': 'Quetta', 'Sindh': 'Karachi', 'KPK': 'Peshawar', 'Punjab': 'Lahore'} .. GENERATED FROM PYTHON SOURCE LINES 244-245 We can also use the following code to achieve the same result .. GENERATED FROM PYTHON SOURCE LINES 245-251 .. code-block:: default capitals = ["Quetta", "Karachi", "Peshawar", "Lahore"] provinces = ["Balochistan", "Sindh", "KPK", "Punjab"] dict(zip(provinces, capitals)) .. rst-class:: sphx-glr-script-out .. code-block:: none {'Balochistan': 'Quetta', 'Sindh': 'Karachi', 'KPK': 'Peshawar', 'Punjab': 'Lahore'} .. GENERATED FROM PYTHON SOURCE LINES 252-257 In above code, we are making use of ``zip``, ``list`` and ``dict`` functions together. This working cab be broken down into following steps: First we make use of ``zip`` function to convert these two lists into a generator. More about generators and zip will come later. .. GENERATED FROM PYTHON SOURCE LINES 257-262 .. code-block:: default provinces_capitals_iterator = zip(provinces, capitals) print(provinces_capitals_iterator) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 263-267 .. code-block:: default provinces_capitals = list(provinces_capitals_iterator) print(provinces_capitals) .. rst-class:: sphx-glr-script-out .. code-block:: none [('Balochistan', 'Quetta'), ('Sindh', 'Karachi'), ('KPK', 'Peshawar'), ('Punjab', 'Lahore')] .. GENERATED FROM PYTHON SOURCE LINES 268-269 Now we can convert `provinces_capitals` into dictionary by making use of ``dict`` function. .. GENERATED FROM PYTHON SOURCE LINES 269-273 .. code-block:: default provinces_capitals_dict = dict(provinces_capitals) print(provinces_capitals_dict) .. rst-class:: sphx-glr-script-out .. code-block:: none {'Balochistan': 'Quetta', 'Sindh': 'Karachi', 'KPK': 'Peshawar', 'Punjab': 'Lahore'} .. GENERATED FROM PYTHON SOURCE LINES 278-282 Operations on dictionaries ========================== Following examples show, how to apply different operations with dictionaries. .. GENERATED FROM PYTHON SOURCE LINES 284-286 ``len`` ------- .. GENERATED FROM PYTHON SOURCE LINES 286-293 .. code-block:: default man = {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1979} len(man) .. rst-class:: sphx-glr-script-out .. code-block:: none 4 .. GENERATED FROM PYTHON SOURCE LINES 296-298 ``in`` ------- .. GENERATED FROM PYTHON SOURCE LINES 298-300 .. code-block:: default print("died" in man) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 301-305 .. code-block:: default del man["died"] print("died" not in man) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 306-307 Repeating the above code will result in error. .. GENERATED FROM PYTHON SOURCE LINES 309-310 We can also combine ``in`` with ``not`` .. GENERATED FROM PYTHON SOURCE LINES 310-312 .. code-block:: default print("city" not in man) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 313-315 ``pop`` --------- .. GENERATED FROM PYTHON SOURCE LINES 317-325 .. code-block:: default man = {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1979} man.pop("died") .. rst-class:: sphx-glr-script-out .. code-block:: none 1979 .. GENERATED FROM PYTHON SOURCE LINES 326-329 .. code-block:: default print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq'} .. GENERATED FROM PYTHON SOURCE LINES 330-331 If we try to remove a non-existing key using ``pop``, it will throw KeyError. .. GENERATED FROM PYTHON SOURCE LINES 331-335 .. code-block:: default # uncomment following line # man.pop("died") # KeyError .. GENERATED FROM PYTHON SOURCE LINES 336-338 However, we can avoid this error by supplying the default value that needs to be returned. .. GENERATED FROM PYTHON SOURCE LINES 338-340 .. code-block:: default man.pop("dob", 19350101) .. rst-class:: sphx-glr-script-out .. code-block:: none 19350101 .. GENERATED FROM PYTHON SOURCE LINES 341-343 Therefore, we can use this method to avoid the error of removing the key from a dictionary if the key is not present in dictionary. .. GENERATED FROM PYTHON SOURCE LINES 345-348 .. code-block:: default man.pop("died", None) .. GENERATED FROM PYTHON SOURCE LINES 349-352 .. code-block:: default print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq'} .. GENERATED FROM PYTHON SOURCE LINES 353-355 ``poopitem`` ------------- .. GENERATED FROM PYTHON SOURCE LINES 357-365 .. code-block:: default man = {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1979} man.popitem() .. rst-class:: sphx-glr-script-out .. code-block:: none ('died', 1979) .. GENERATED FROM PYTHON SOURCE LINES 366-369 .. code-block:: default print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq'} .. GENERATED FROM PYTHON SOURCE LINES 370-373 .. code-block:: default man.popitem() .. rst-class:: sphx-glr-script-out .. code-block:: none ('citizenship', 'Iraq') .. GENERATED FROM PYTHON SOURCE LINES 374-377 .. code-block:: default print(man) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': 'Baqir -al- Sadr', 'born': 1935} .. GENERATED FROM PYTHON SOURCE LINES 378-383 ``get`` -------- This method can also be used for accessing the values in dictionary. It returns `None` if the key is not present and we can set the default value for a key if the value is not already present. .. GENERATED FROM PYTHON SOURCE LINES 385-393 .. code-block:: default man = {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1979} print(man.get("city")) .. rst-class:: sphx-glr-script-out .. code-block:: none None .. GENERATED FROM PYTHON SOURCE LINES 394-397 .. code-block:: default man.get("city", "Baghdad") .. rst-class:: sphx-glr-script-out .. code-block:: none 'Baghdad' .. GENERATED FROM PYTHON SOURCE LINES 398-401 If a key is not present in a dictionary, and we try to access its value, we can avoid the KeyError by setting the default value of that key .. GENERATED FROM PYTHON SOURCE LINES 401-403 .. code-block:: default print(man.get('age', 44)) .. rst-class:: sphx-glr-script-out .. code-block:: none 44 .. GENERATED FROM PYTHON SOURCE LINES 404-407 ``copy`` --------- Simple object assignment with ``=`` makes a shallow copy. .. GENERATED FROM PYTHON SOURCE LINES 409-420 .. code-block:: default man1 = {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1979} man2 = man1 man2["name"] = "Mutahri" print(man1) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': 'Mutahri', 'born': 1935, 'citizenship': 'Iraq', 'died': 1979} .. GENERATED FROM PYTHON SOURCE LINES 421-424 .. code-block:: default print(man2) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': 'Mutahri', 'born': 1935, 'citizenship': 'Iraq', 'died': 1979} .. GENERATED FROM PYTHON SOURCE LINES 425-427 so even though we changed the ``name`` of ``man2``, but ``name`` of ``man1`` is also changed. .. GENERATED FROM PYTHON SOURCE LINES 429-439 .. code-block:: default man1 = {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1979} man2 = man1.copy() man2["name"] = "Mutahri" .. GENERATED FROM PYTHON SOURCE LINES 440-444 .. code-block:: default print(man1) print(man2) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1979} {'name': 'Mutahri', 'born': 1935, 'citizenship': 'Iraq', 'died': 1979} .. GENERATED FROM PYTHON SOURCE LINES 445-448 Now we don't see ``name`` of ``man1`` dictionary from getting changed. This is because we made a copy of ``man1`` and set this copy to ``man2``. After that we changed ``man2`` key. .. GENERATED FROM PYTHON SOURCE LINES 450-461 .. code-block:: default men1 = {1: {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1980}, 2: {"name": "Mutahri", "born": 1919, "citizenship": "Iran", "died": 1979}} men2 = men1.copy() men2[2]["name"] = "Murtaza Mutahri" print(men1) print(men2) .. rst-class:: sphx-glr-script-out .. code-block:: none {1: {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1980}, 2: {'name': 'Murtaza Mutahri', 'born': 1919, 'citizenship': 'Iran', 'died': 1979}} {1: {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1980}, 2: {'name': 'Murtaza Mutahri', 'born': 1919, 'citizenship': 'Iran', 'died': 1979}} .. GENERATED FROM PYTHON SOURCE LINES 462-469 Even though we made a copy of ``men1`` dictionary using ``copy`` method and changed only ``men2`` dictionary, but contents of ``men1`` are still changed when we change ``men2``. This is because ``copy`` method still makes a shallow copy of the dictionaries (1,2) which are inside the dictionary (men1). Same is true for `list` in the dictionaries. .. GENERATED FROM PYTHON SOURCE LINES 471-481 .. code-block:: default books1 = {"AlSadr": ["Our Philosophy", "Our Economy"], "Mutahri": ["Divine Justice", "Man and Destiny"]} books2 = books1.copy() books2["Mutahri"][1] = "The goal of life" print(books1) print(books2) .. rst-class:: sphx-glr-script-out .. code-block:: none {'AlSadr': ['Our Philosophy', 'Our Economy'], 'Mutahri': ['Divine Justice', 'The goal of life']} {'AlSadr': ['Our Philosophy', 'Our Economy'], 'Mutahri': ['Divine Justice', 'The goal of life']} .. GENERATED FROM PYTHON SOURCE LINES 482-485 How to copy a dictionary which may contain several dictionaries? we can make use of ``copy`` by iterating over dictionary .. GENERATED FROM PYTHON SOURCE LINES 485-498 .. code-block:: default import copy men1 = {1: {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1980}, 2: {"name": "Mutahri", "born": 1919, "citizenship": "Iran", "died": 1979}} men2 = copy.copy(men1) men2[2]["name"] = "Murtaza Mutahri" print(men1) print(men2) .. rst-class:: sphx-glr-script-out .. code-block:: none {1: {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1980}, 2: {'name': 'Murtaza Mutahri', 'born': 1919, 'citizenship': 'Iran', 'died': 1979}} {1: {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1980}, 2: {'name': 'Murtaza Mutahri', 'born': 1919, 'citizenship': 'Iran', 'died': 1979}} .. GENERATED FROM PYTHON SOURCE LINES 499-501 if we iterate through each key, value pair of dictionary and copy it individually, we can avoid this shallow copying .. GENERATED FROM PYTHON SOURCE LINES 501-524 .. code-block:: default def copy_dict(d: dict) -> dict: """makes deepcopy of a dictionary without cloning it""" assert isinstance(d, dict) new_dict = {} for k, v in d.items(): new_dict[k] = copy.copy(v) return new_dict men1 = {1: {"name": "Baqir -al- Sadr", "born": 1935, "citizenship": "Iraq", "died": 1980}, 2: {"name": "Mutahri", "born": 1919, "citizenship": "Iran", "died": 1979}} men2 = copy_dict(men1) men2[2]["name"] = "Murtaza Mutahri" print(men1) print(men2) .. rst-class:: sphx-glr-script-out .. code-block:: none {1: {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1980}, 2: {'name': 'Mutahri', 'born': 1919, 'citizenship': 'Iran', 'died': 1979}} {1: {'name': 'Baqir -al- Sadr', 'born': 1935, 'citizenship': 'Iraq', 'died': 1980}, 2: {'name': 'Murtaza Mutahri', 'born': 1919, 'citizenship': 'Iran', 'died': 1979}} .. GENERATED FROM PYTHON SOURCE LINES 525-526 but what if dictionary inside the dictionary further contains dictionaries .. GENERATED FROM PYTHON SOURCE LINES 526-538 .. code-block:: default men1 = {1: {"iraq": {'person1': {'name': 'sadr'}, 'person2': {'name': 'hakim'}}, "iran": {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} men2 = copy_dict(men1) men2[1]["iraq"]['person1']['name'] = "baqir al sadr" print(men1) print(men2) .. rst-class:: sphx-glr-script-out .. code-block:: none {1: {'iraq': {'person1': {'name': 'baqir al sadr'}, 'person2': {'name': 'hakim'}}, 'iran': {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} {1: {'iraq': {'person1': {'name': 'baqir al sadr'}, 'person2': {'name': 'hakim'}}, 'iran': {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} .. GENERATED FROM PYTHON SOURCE LINES 539-540 although we changed ``name`` of ``person1`` in ``men2`` but it is also changed in ``men1``. .. GENERATED FROM PYTHON SOURCE LINES 542-544 we can achieve this by calling the parent function again every time the value is a dictionary i.e. calling ``copy_dict`` function inside ``copy_dict`` function. .. GENERATED FROM PYTHON SOURCE LINES 544-569 .. code-block:: default def copy_dict(d: dict) -> dict: """makes deepcopy of a dictionary without cloning it""" assert isinstance(d, dict) new_dict = {} for k, v in d.items(): if isinstance(v, dict): new_dict[k] = copy_dict(v) else: new_dict[k] = copy.copy(v) return new_dict men1 = {1: {"iraq": {'person1': {'name': 'sadr'}, 'person2': {'name': 'hakim'}}, "iran": {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} men2 = copy_dict(men1) men2[1]["iraq"]['person1']['name'] = "baqir al sadr" print(men1) print(men2) .. rst-class:: sphx-glr-script-out .. code-block:: none {1: {'iraq': {'person1': {'name': 'sadr'}, 'person2': {'name': 'hakim'}}, 'iran': {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} {1: {'iraq': {'person1': {'name': 'baqir al sadr'}, 'person2': {'name': 'hakim'}}, 'iran': {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} .. GENERATED FROM PYTHON SOURCE LINES 570-573 However, there is simpler solution to this problem. Instead of writting a function like `copy_dict`, which copies each object from dictionary one by one, we can simply use ``deepcopy`` function from ``copy`` module. .. GENERATED FROM PYTHON SOURCE LINES 573-585 .. code-block:: default from copy import deepcopy men1 = {1: {"iraq": {'person1': {'name': 'sadr'}, 'person2': {'name': 'hakim'}}, "iran": {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} men2 = deepcopy(men1) men2[1]["iraq"]['person1']['name'] = "baqir al sadr" print(men1) print(men2) .. rst-class:: sphx-glr-script-out .. code-block:: none {1: {'iraq': {'person1': {'name': 'sadr'}, 'person2': {'name': 'hakim'}}, 'iran': {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} {1: {'iraq': {'person1': {'name': 'baqir al sadr'}, 'person2': {'name': 'hakim'}}, 'iran': {'person1': {'name': 'mutahri'}, 'person2': {'name': 'shariati'}}}} .. GENERATED FROM PYTHON SOURCE LINES 586-590 ``update`` ---------- This method updates an existing dictionary. %% .. GENERATED FROM PYTHON SOURCE LINES 590-597 .. code-block:: default books = {"AlSadr": ["Our Philosophy", "Our Economy"], "Mutahri": ["Divine Justice", "Man and Destiny"] } new_books = {"Legenhausen": ["Religious pluralism", "Hegel's ethics"]} .. GENERATED FROM PYTHON SOURCE LINES 598-599 The method does not return anything. Only the original dictionary is changed. .. GENERATED FROM PYTHON SOURCE LINES 599-604 .. code-block:: default books.update(new_books) print(books) .. rst-class:: sphx-glr-script-out .. code-block:: none {'AlSadr': ['Our Philosophy', 'Our Economy'], 'Mutahri': ['Divine Justice', 'Man and Destiny'], 'Legenhausen': ['Religious pluralism', "Hegel's ethics"]} .. GENERATED FROM PYTHON SOURCE LINES 605-609 Merging dictionaries ========================== The update merges one dictionary into other. If we want to keep both dictionaries intact and create a new one by merging them together, we can do this as following (starting from python 3.5) .. GENERATED FROM PYTHON SOURCE LINES 611-622 .. code-block:: default old_books = {"AlSadr": ["Our Philosophy", "Our Economy"], "Mutahri": ["Divine Justice", "Man and Destiny"] } new_books = {"Legenhausen": ["Religious pluralism", "Hegel's ethics"]} books = {**old_books, **new_books} print(books) .. rst-class:: sphx-glr-script-out .. code-block:: none {'AlSadr': ['Our Philosophy', 'Our Economy'], 'Mutahri': ['Divine Justice', 'Man and Destiny'], 'Legenhausen': ['Religious pluralism', "Hegel's ethics"]} .. GENERATED FROM PYTHON SOURCE LINES 623-624 We can verify that `old_books` and `new_books` dictionaries are intact. .. GENERATED FROM PYTHON SOURCE LINES 624-629 .. code-block:: default print(old_books) print(new_books) .. rst-class:: sphx-glr-script-out .. code-block:: none {'AlSadr': ['Our Philosophy', 'Our Economy'], 'Mutahri': ['Divine Justice', 'Man and Destiny']} {'Legenhausen': ['Religious pluralism', "Hegel's ethics"]} .. GENERATED FROM PYTHON SOURCE LINES 630-631 We can even provide a new key value pair. .. GENERATED FROM PYTHON SOURCE LINES 631-636 .. code-block:: default books = {**old_books, "Iqbal": "reconstruction", **new_books} print(books) .. rst-class:: sphx-glr-script-out .. code-block:: none {'AlSadr': ['Our Philosophy', 'Our Economy'], 'Mutahri': ['Divine Justice', 'Man and Destiny'], 'Iqbal': 'reconstruction', 'Legenhausen': ['Religious pluralism', "Hegel's ethics"]} .. GENERATED FROM PYTHON SOURCE LINES 637-640 The double asterisk ``**``, in fact, just unpacks the dictionary into key value pairs and then we construct a new dictionary by putting the unpacked key value pairs inside curly brackets "{}". .. GENERATED FROM PYTHON SOURCE LINES 642-645 .. code-block:: default print({'x': 1, **{'y': 2}}) .. rst-class:: sphx-glr-script-out .. code-block:: none {'x': 1, 'y': 2} .. GENERATED FROM PYTHON SOURCE LINES 646-648 For backup compatability, we better use the ``update`` method that can run on versions before 3.5 as follows .. GENERATED FROM PYTHON SOURCE LINES 650-655 .. code-block:: default books = old_books.copy() books.update(new_books) print(books) .. rst-class:: sphx-glr-script-out .. code-block:: none {'AlSadr': ['Our Philosophy', 'Our Economy'], 'Mutahri': ['Divine Justice', 'Man and Destiny'], 'Legenhausen': ['Religious pluralism', "Hegel's ethics"]} .. GENERATED FROM PYTHON SOURCE LINES 656-657 We can also merge two dictionaries with another method. .. GENERATED FROM PYTHON SOURCE LINES 659-668 .. code-block:: default old_books = {"AlSadr": ["Our Philosophy", "Our Economy"], "Mutahri": ["Divine Justice", "Man and Destiny"]} new_books = {"Legenhausen": ["Religious pluralism", "Hegel's ethics"]} books = dict(list(old_books.items()) + list(new_books.items())) print(books) .. rst-class:: sphx-glr-script-out .. code-block:: none {'AlSadr': ['Our Philosophy', 'Our Economy'], 'Mutahri': ['Divine Justice', 'Man and Destiny'], 'Legenhausen': ['Religious pluralism', "Hegel's ethics"]} .. GENERATED FROM PYTHON SOURCE LINES 669-675 **Question:** Write code to print the value of second key of the following dictionary i.e. "Hassan". .. code-block:: python x = {1: "ali", 2: "hassan", 3: "hussain"} .. GENERATED FROM PYTHON SOURCE LINES 677-683 **Question:** Write code to tell the date of birth and death of the `Ali` from the following dictionary. .. code-block:: python x = {"Ali": {"born": 600, "died": 661}, "Hassan": {"born": 625, "died": 670}, "Hussain": {"born": 626, "died": 680}} .. GENERATED FROM PYTHON SOURCE LINES 686-694 **Question:** What will be output of following code? .. code-block:: python x = {1: "ali", 2: "hassan", 3: "hussain"} y = {1: "ali", 2: "hassan", 3: "hussain", 4: "Ali"} print(x.get(4, y.get(4)) .. GENERATED FROM PYTHON SOURCE LINES 696-704 **Question:** Change the contents of dictionary `y` in such a way the following code throws ``KeyError`` .. code-block:: python x = {1: "ali", 2: "hassan", 3: "hussain"} y = ?? print(x.get(4, y.get(4)) # should throw KeyError .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.023 seconds) .. _sphx_glr_download_auto_examples_basics_dictionaries.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/AtrCheema/python-seekho/master?urlpath=lab/tree/notebooks/auto_examples/basics/dictionaries.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: dictionaries.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: dictionaries.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_