Table of Contents

    Understanding Python Dictionaries: A Beginner's Guide to Key-Value Pairs

    A Dictionary is a data structure that operates in a similar manner to the hash tables. The hash tables are simply an array of information with key-valued pairs. The Python dictionaries are associative arrays, or hashes, that have key-valued pairs where the dictionary key can take any Python data type. However, numbers or strings are the most common methods of defining the
    dictionary keys. However, the dictionary values can take any arbitrary Python object.

    Python Dictionaries are enclosed by the curly brackets { }, and the values are assigned and accessed using the square brackets []. Here’s an example code:

    mydictionary = {}
    mydictionary[1] = "This is 1."
    mydictionary['one'] = "This is 2"
    smalldictionary = {"name": "Ronald Olsen", "code":722848386, "dept":"IT"}

    Here’s an example an illustration of Python Dictionaries:

    print(mydictionary[1]) # Prints the value for "one" key
    print(mydictionary['one']) # Prints the value for 2 key
    print(smalldictionary) # Prints the complete dictionary
    print(smalldictionary.keys()) # Prints all the keys

    Output

    This is 1.
    This is 2
    {'name': 'Ronald Olsen', 'code': 722848386, 'dept': 'IT'}
    dict_keys(['name', 'code', 'dept'])
    Python Dictionary vs Set

    Points to remember for Dictionaries

    1. Dictionaries in Python are a collection of some key-value pairs.
    2. These are mutable and unordered collection with elements in the form of a key : value pairs that associate keys to values.
    3. The keys of dictionaries are immutable type and unique.
    4. To manipulate dictionaries functions are : len(), clear(), has_key(),items(), keys(), values(), update().
    5. The membership operators in and not in work with dictionary keys only.