Online-Academy
Look, Read, Understand, Apply

Dictionary

Dictionary

Dictionaries are unordered, mutable collections of key-value pairs. Beyond basic usage (dict[key] = value),


def add(a, b): return a + b
def sub(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b): return a / b if b != 0 else "Error"


if __name__ == "__main__":
    
    dictionary = {
        "name":"dinesh",
        "address":"baneshwor",
        "hobby":["reading",'watching movies',"watching tennis","watching cricket"],
    }

    print(dictionary)
    # Adding new Item to dictionary using update method
    dictionary.update({"fav_movies":["Gone with the Wind","Borken Arrow"]})
    
    print(dictionary)

    # Adding new Item to dictionary
    dictionary["books"] = ["DSA","DBMS","Programming"]
    print(dictionary)
    
    # Accesing dictionary items
    print("Name: ",dictionary["name"])
    
    l = dictionary["books"]
    print("Books: ",l)
    print("Favorite Movies: ",dictionary["fav_movies"])
    
    print("Keys: ",dictionary.keys())
    print("Values: ",dictionary.values())
    print("Items: ",dictionary.items())
    
    #changing item of dicitonary
    dictionary["address"] = "New Baneshwor"
    print("New Address: ",dictionary["address"])
    
    #chaing item of dictionary using update method
    dictionary.update({"address":"New Baneshowr, Kathmandu"})
    print("Address changed using update : ",dictionary["address"])
    
    #removing items from dictionary
    dictionary.pop("address")
    print("After removing address: ",dictionary)
    
    #REMOVING LAST ITEM INSERTED TO THE DICTIONARY  -  popitem()
    dictionary.popitem()
    
    
    #looping through dictionary
    print("using for loop to accessing dictionary items: only keys will be displayed")
    for x in dictionary:
        print(x)
    
    #display values of keys
    for x in dictionary:
        print(dictionary[x])
        
    #displaying values using values method
    for x in dictionary.values():
        print("using values(): ",x)
        
    # displaying both keys and values
    for k,v in dictionary.items():
        print(k," : ",v)            
    #removing all items from dictinary
    dictionary.clear()
    print("After clear: ",dictionary)
        
    # deleting dictionary completely
    del dictionary
    # print(dictionary) this will result in error
    
    #using methods as values in dictionary
    ops = {'+': add, '-': sub}
    print(ops['+'](10, 5))  # Output: 15

    d = {'apple': 3, 'banana': 1, 'orange': 2}
    sorted_by_value = dict(sorted(d.items(), key=lambda item: item[1]))
    print(sorted_by_value)  # Output: {'banana': 1, 'orange': 2, 'apple': 3}
    d = {'x': 10, 'y': 20}
    print(d.keys())    # dict_keys(['x', 'y'])
    print(d.values())  # dict_values([10, 20])
    print(d.items())   # dict_items([('x', 10), ('y', 20)])

    students = {
        'Alice': {'age': 20, 'grade': 'A'},
        'Bob': {'age': 22, 'grade': 'B'}
    }
    print(students['Alice']['grade'])  # Output: A

    students = {
        'Alice': {'Math': 90, 'English': 85, 'Science': 92},
        'Bob': {'Math': 78, 'English': 82, 'Science': 88},
    }

    # Average grade for each student
    for name, subjects in students.items():
        avg = sum(subjects.values()) / len(subjects)
        print(f"{name}: {avg:.2f}")

    #Create a dictionary of squares of even numbers only:
    squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
    print(squares)  # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

    # Dictionary of Functions (Dispatch Table): Dynamic function selection:
    operations = {'+': add, '*': multiply, '/': divide}

    a, b = 10, 5
    op = '*'
    result = operations[op](a, b)
    print(result)  # Output: 50

    # Using setdefault() for Grouping
    names = ['Alice', 'Bob', 'Charlie', 'David', 'Amanda']
    groups = {}

    for name in names:
        key = name[0]
        groups.setdefault(key, []).append(name)

    print(groups)
    # Output: {'A': ['Alice', 'Amanda'], 'B': ['Bob'], 'C': ['Charlie'], 'D': ['David']}