Python Dictionary

What is Dictionary?

  • Dictionary is a python data type that is used to store 'key-value' pairs.
  • It enables to quickly retrieve, add, remove, modify, values using a key.
  • Dictionary is very similar to what we call associative array or hash on other languages.
  • Dictionaries are mutable.
  • No index value concept in dictionary

  • How to create Dictionary?

  • Dictionaries are represented by enclosed curly braces {}
  • Each key is separated from its value by a colon (:) and the items are separated by commas(,)
  • # Empty Dictionary
    my_dict = {}
    print("Empty dictionary is created",my_dict)
    
    # Dictionary with Integer keys
    colors = {1:'red', 2:'green', 3:'Yellow'}
    print("Dictionary with integer keys are created ",colors)
    
    # Dictionary with mixed keys
    my_dict = {'name': 'vinoth', 1: ['red', 'green']}
    print("Dictionary with mixed keys are created",my_dict)
    
    # Checking the Type
    print(type(my_dict))
    
    Output:
    Empty dictionary is created {}
    Dictionary with integer keys are created  {1: 'red', 2: 'green', 3: 'Yellow'}
    Dictionary with mixed keys are created {'name': 'vinoth', 1: ['red', 'green']}
    <class 'dict'>
    

    Note - No duplicate keys are allowed

  • When duplicate keys encountered during assignment, the last assigned key will be considered
  • # Dictionary with duplicate keys
    colors = {1:'red', 2:'green', 3:'Yellow', 2:'blue'} # key 2 mentioned twice
    print("Key 2 is updated with last assigned value",colors)
    
    Output:
    Key 2 is updated with last assigned value {1: 'red', 2: 'blue', 3: 'Yellow'}
    

    How to access elements from a dictionary?

  • To access dictionary elements, you can use the enclosed square brackets along with the key to obtain its value
  • # Access the key which is available in the dictionary 
    mydetails = {'name': 'Vinoth','age':30, 'address': 'Chennai'}
    
    print(mydetails['name'])
    print(mydetails['address'])
    
    Output:
    Vinoth
    Chennai
    
    # Access the key which is not available in the dictionary - KeyError will be displayed
    print(mydetails['phonenumber']) 
    
    Output:
    KeyError: Traceback (most recent call last)
    <ipython-input-28-355917c6fc04> in <module>()
          1 # Access the key which is not available in the dictionary
    ----> 2 print(mydetails['phonenumber'])
    
    KeyError: 'phonenumber'
    

    How to access the element using Get Method?

  • It returns value of key, if key is not found it returns None, instead of throwing KeyError exception
  • #Create a dictionary
    mydetails = {'name': 'Vinoth','age':30, 'address': 'Chennai'}
    
    # Access the key which is available in the dictionary 
    print(mydetails.get('name'))
    
    # Access the key which is not available in the dictionary 
    print(mydetails.get('phonenumber'))
    
    Output:
    Vinoth
    None
    

    How to add elements(key) in a dictionary?

  • Dictionary are mutable. We can add new items or change the value of existing items using assignment operator '='
  • If the key is already present, value gets updated, else a new key is added
  • #Create a dictionary
    mydetails = {'name': 'Vinoth','age':30, 'address': 'Chennai'}
    
    # Add phonenumber
    mydetails['phonenumber'] = '+91-6383544892'
    
    print(mydetails)
    
    Output:
    {'name': 'Vinoth', 'age': 30, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
    

    How to change/update existing element(value) in a dictionary?

    # Updating the value
    mydetails['age'] = 31
    
    print(mydetails)
    
    Output:
    {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
    

    How to delete an elements in a dictionary?

    1. pop() Method

    pop() Method - Remove the item from the dictionary, if the key is not found KeyError will be thrown. It will also returns the removed value

    #Create a dictionary
    mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
    
    #Remove a particular item
    print(mydetails.pop('phonenumber'))
    print(mydetails)
    
    Output:
    +91-6383544892
    {'name': 'Vinoth', 'age': 31, 'address': 'Chennai'}
    

    2. popitem() Method

    popitem() Method - To remove and return an arbitrary item (key, value)

    #Create a dictionary
    mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
    
    # It remove the last item in the dictionary
    mydetails.popitem()
    
    print(mydetails)
    
    Output:
    {'name': 'Vinoth', 'age': 31, 'address': 'Chennai'}
    

    3. del Keyword

    del keyword to remove individual item or the entire dictionary itself.

    #Sample code to delete a particular item
    # Dictionary with cubes of number
    cube = {1:1, 2:8, 3:27, 4:64, 5:125}
    
    # Delete particular key
    del cube[4]
    
    print(cube)
    
    Output:
    {1: 1, 2: 8, 3: 27, 5: 125}
    
    #Sample code to delete the entire dictionary
    # Dictionary with cubes of number
    cube = {1:1, 2:8, 3:27, 4:64, 5:125}
    
    # Delete the entire dictionary
    del cube
    
    # NameError is displayed as the entire dictionary is deleted
    print(cube) 
    
    Output:
    NameError: Traceback (most recent call last)
    <ipython-input-50-7e054bd83a54> in <module>()
          8 
          9 # NameError is displayed as the entire dictionary is deleted
    ---> 10 print(cube)
    
    NameError: name 'cube' is not defined
    

    4. clear() Method

    Clear Method - All the items can be removed at once, without deleting the dictionary

    # Dictionary with cubes of number
    cube = {1:1, 2:8, 3:27, 4:64, 5:125}
    
    #Remove all items
    cube.clear()
    
    print("Empty dictionary is displayed",cube)
    
    Output:
    Empty dictionary is displayed {}
    

    Looping items in the dictionary

    # Dictionary with cubes of number
    cube = {1:1, 2:8, 3:27, 4:64, 5:125}
    
    for num in cube:
        print("Cube of",num,"is",cube[num])
    
    Output:
    Cube of 1 is 1
    Cube of 2 is 8
    Cube of 3 is 27
    Cube of 4 is 64
    Cube of 5 is 125
    

    Dictionary Methods

    1. length - len()

    Length of dictionary, i.e. the number of elements in the dictionary.

    #Create a dictionary
    mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
    print("length of the Dictionary is",len(mydetails))
    
    Output:
    length of the list is 4
    

    2. Membership - ' in and not in' Operator

    #Create a dictionary
    mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
    
    # Sample Code for 'in' operator - True if key is in dictionary.
    print('name' in mydetails)
    
    # Sample Code for 'not in' operator -True if key is not in dictionary.
    print('email' not in mydetails)
    
    Output:
    True
    True
    

    3. sorted()

  • The sorted() method sorts the elements of a given dictionary in a specific order - Ascending or Descending.
  • By default in ascending order
  • Sorting will be carried by taking key as reference
  • # Sort the vowels in Ascending order
    vowels = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
    print('Sorted Dictionary:', sorted(vowels))
    
    Output:
    Sorted Dictionary: ['a', 'e', 'i', 'o', 'u']
    
    # Setting reverse=True sorts the dictionary in the descending order
    vowels = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
    print('Sorted Dictionary (in Descending):', sorted(vowels,reverse=True))
    
    Output:
    Sorted Dictionary (in Descending): ['u', 'o', 'i', 'e', 'a']
    

    4. keys()

  • Return keys in the dictionary as tuples
  • #Create a dictionary
    mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
    print(mydetails.keys())
    
    Output:
    dict_keys(['name', 'age', 'address', 'phonenumber'])
    

    5. values()

  • Return keys in the dictionary as tuples
  • #Create a dictionary
    mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
    print(mydetails.values())
    
    Output:
    dict_values(['Vinoth', 31, 'Chennai', '+91-6383544892'])
    

    6. items()

  • Return a new view of the dictionary items (key, value) as tuples
  • # Dictionary with cubes of number
    cube = {1:1, 2:8, 3:27, 4:64, 5:125}
    print(cube.items()) 
    
    Output:
    dict_items([(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)])
    

    7. copy()

  • Return a shallow copy of the dictionary. It doesn't modify the original dictionary.
  • # Dictionary with cubes of number
    cube = {1:1, 2:8, 3:27, 4:64, 5:125}
    
    dictcopy = cube.copy()
    
    print('Original:', cube)
    print('New:', dictcopy)
    
    Output:
    Original: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
    New: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
    

    8. update()

  • The update() method inserts the specified items to the dictionary at the end, if the value is not present.
  • In case if the value is already existing, it will be updated with new value.
  • The specified items can be a dictionary, or an iterable object.

  • Inserting the new value

    
    # Dictionary with car details
    car = {"brand": "Audi",  "model": "A7",  "year": 2019}
    
    car.update({"color": "White"})
    print(car) 
    
    Output:
    {'brand': 'Audi', 'model': 'A7', 'year': 2019, 'color': 'White'}
    

    Updating the existing value

    # Dictionary with car details
    car = {"brand": "Audi",  "model": "A7", "color":"Blue" , "year": 2019}
    
    car.update({"color": "White"})
    print(car) 
    
    Output:
    {'brand': 'Audi', 'model': 'A7', 'color': 'White', 'year': 2019}
    

    Update with an iterable.

    # Dictionary with car details
    car = {"brand": "Audi",  "model": "A7", "year": 2019}
       
    # Updating with multiple key and values 
    car.update(cost = '68000$', color = 'White') 
    print("Dictionary after updation:",car) 
    
    Output:
    Dictionary after updation:
    {'brand': 'Audi', 'model': 'A7', 'year': 2019, 'cost': '68000$', 'color': 'White'}

    9. fromkeys()

    The fromkeys() method creates a new dictionary from the given sequence of elements with a value provided by the user.

    The fromkeys() method takes two parameters:

  • sequence - sequence of elements which is to be used as keys for the new dictionary
  • value (Optional) - value which is set to each each element of the dictionary
  • #  Creating a dictionary from a sequence of keys with value
    # vowels keys
    mykeys = {'a', 'e', 'i', 'o', 'u' }
    value = 'vowels'
    
    vowels = dict.fromkeys(mykeys, value)
    print(vowels)
    
    Output:
    {'o': 'vowels', 'a': 'vowels', 'e': 'vowels', 'i': 'vowels', 'u': 'vowels'}
    

    10. setdefault()

    The setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary.

    if key is not in the dictionary.

    # Sample code 
    employee = {'name': 'Muthu'}
    
    salary = employee.setdefault('salary')
    print("Employee details :",employee)
    print('salary=',salary)
    
    Output:
    Employee details : {'name': 'Muthu', 'salary': None}
    salary= None
    

    if key is not in the dictionary and default_value is provided

    # Sample code  
    employee = {'name': 'Muthu'}
    
    company = employee.setdefault('company', 'CTS')
    print("Employee details :",employee)
    print('company=',company)
    
    Output:
    Employee details : {'name': 'Muthu', 'company': 'CTS'}
    company= CTS
    

    11. dir()

    Get list of all available methods and attributes of dictionary

    mydict = {}
    print(dir(mydict))
    
    Output:
    ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__',
    '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__',
    '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__',
    '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__',
    '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys',
    'pop', 'popitem', 'setdefault', 'update', 'values']

    Dictionary Comprehension

  • Dictionary comprehension is an elegant and concise way to create new dictionary from an iterable in Python.
  • It consists of an expression pair (key: value) followed by for statement inside curly braces {}.
  • #Using Dictionary comprehension
    cubes = {x: x**3 for x in range(10)}
    print(cubes)
    
    Output:
    {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
    

    Q. we have a list of fruits and we can use dict comprehension to create a dictionary with fruits, the list elements as the keys and the length of each string as the values

    # create list of fruits
    fruits = ['apple', 'mango', 'banana']
    
    # dict comprehension to create dict with fruit name as keys
    {f:len(f) for f in fruits}
    
    Output:
    {'apple': 5, 'mango': 5, 'banana': 6}
    
    Total Website Visits: 40449
    © Copyright 2018 - 2020. All Rights Reserved.

    Developed by Vinoth Rathinam