Introduction to Dictionaries in Python

05 min read

A dictionary is similar to a list, where a list is a linear collection in order whereas a Dictionary can be defined as a "bag" of values, each with its own label.  Every item in the list has a unique key attached to it representing the item in the dictionary. Syntax to create an empty dictionary, and further add elements to it with keys is shown below:

In a dictionary, the item and its key are linked using a (:) colon and items are separated with a comma (,). All the items and their key values are depicted between {} parenthesis.

# say 'purse' is the dictionary that needs to be created with elements such as money, candy, keys inside it >>

purse = dict() # created an empty dictionary named purse
purse['money'] = 12 # placed a new item called money in the dict with a key of 12 assigned to it.
purse[ 'candy'] =3
purse['keys'] =75
purse['Name of owner'] = 'FACE_Prep'

print(purse)

Output:
{'candy': 3, 'keys': 75, 'money': 12, 'Name of owner': 'FACE_Prep'}

 
 
Adding an element to the dictionary: 
You can add a new item with a key or update a previously developed dictionary. To update we can use the previous example, 
 
purse['keys'] =76            # the key value assigned is now updated from 75 to 76 
purse['ticket'] = 33         # a new item ticket is added to the dictionary now
print(purse)

Output:
{'candy': 3, 'keys': 76, 'money': 12, 'Name of owner': 'FACE_Prep', 'ticket' : 33}
 
 
Deleting an item from the dictionary:
The following code can be used to delete one or more items in a dictionary under user-specified instructions.
 
purse = {'candy': 3, 'keys': 75, 'money': 12, 'Name of owner': 'FACE_Prep'}
del purse['candy']                         # remove entry with key 'candy' from purse
purse.clear()                                    # remove all entries in purse dictionary. It becomes an empty list
del purse                                           # deletes the dictionary completely from the program.
 
 
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error