Understanding Python Dictionary
Tags: python, django, webdev
Published: 2020-04-21 10:19:37

In Python, dictionaries are `associative arrays` which store values in the form of 'key' and 'value' pair. Dictionaries are completely different from `list` and `tuples` as they are automatically indexed and only values are provided by the user.

But in the dictionary, we can provide both `key` and `value`. which means we can alter, modify and delete dictionary and its key, values.

**Example** : To creating empty dictonary use `{}` or we can use dictonary constructor 'dict()'.

    d = {}
    di = dict()
    
    print(d)
    print(di)
    
    #PYTHON OUTPUT
    {}
    {}

**Example:** To add values in dictionary

    d = {
        'user_id' : 1,
        'username' : 'Jake',
        'age' : 25,
        'salary' : 95000.75,
    }
    
    di = dict(
        user_id=2,
        username='Sushant',
        age=29,
        salary=105000.50
    )
    
    print('Dictonary using curly brackets')
    print(d)
    
    print('n') #next line
    
    print('Dictonary using dict constructor')
    print(di)
    
    #PYTHON OUTPUT
    Dictonary using curly brackets
    {'user_id': 1, 'username': 'Jake', 'age': 25, 'salary': 95000.75}
    
    
    Dictonary using dict constructor
    {'user_id': 2, 'username': 'Sushant', 'age': 29, 'salary': 105000.5}

**Example:** Values from dictionary can be accessed using keys or by `get()` method

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    print(d['username'])
    print(d.get('username'))
    
    #PYTHON OUTPUT
    Jake
    Jake

**Example**: Updating values in dictionary.

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    d['username']='Rohit'
    
    print(d['username'])
    
    #PYTHON OUTPUT
    Rohit

Appending new item in dictionary can be achieved by simply giving the name of key and value and it will be added in the bottom of dictionary.

**Syntax:**

    dict['key'] = 'value'

**Example**

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    d['date_of_birth'] = '1990-03-22'
    
    print(d)
    
    #PYTHON OUTPUT
    {'user_id': 1, 'username': 'Jake', 'age': 25, 'salary': 95000.75, 'date_of_birth': '1990-03-22'}

There are various method to remove a item from dictionary

*   Use `del` keyword by calling dictionary with a key name to delete. This will delete the item completely.
*   Use `pop()` method by specifying key name inside parentheses.

**Syntax**

    dict.pop('key_name')

*   Use `popitem()` this will remove the last key and value from Dictionary.

Syntax

    dict.popitem()

**Example**

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    del d['username'] #key 'username' will be removed from dictonary
    
    print(d)
    
    #PYTHON OUTPUT
    {'user_id': 1, 'age': 25, 'salary': 95000.75}

**Example** : remove use `pop()` method.

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    d.pop('username')
    print(d)
    
    #PYTHON OUTPUT
    {'user_id': 1, 'age': 25, 'salary': 95000.75}

**Example** : remove using 'popitem()' method.

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    d.popitem() #this method will remove the last item from dictonary in this case it is 'salary'
    print(d)
    
    #PYTHON OUTPUT
    {'user_id': 1, 'username': 'Jake', 'age': 25}

To empty dictonary use `clear()` method.

Syntax

    dict.clear()

**Example**

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    d.clear()
    print(d)
    
    #PYTHON OUTPUT
    {} #we get the empty dictonary

To delete dictionary completely use `del` keyword before dictionary variable.

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    del d
    print(d)
    
    #PYTHON ERROR OUTPUT
    NameError: name 'd' is not defined #because we have deleted the dictonary

Check if a key exists in dictionary

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    if 'username' in d:
        print('Exits')
    else:
        print('Does not exits')
    
    #PYTHON OUTPUT
    Exits

To check if a given value exists in dictionary use `values()` method.

**Example**

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    if 'Jake' in d.values():
        print('Exits')
    else:
        print('Does not exits')
    
    #PYTHON OUTPUT
    Exits

**Example**: To count the number of items present in dictionary use `len()` method.

    d = {
    'user_id' : 1,
    'username' : 'Jake',
    'age' : 25,
    'salary' : 95000.75,
    }
    
    print(len(d))
    
    #PYTHON OUTPUT
    4

This article was taken from [Working with Dictionary in Python](http://thecodelearners.com/working-with-dictionary-in-python/)