__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------==================================================================================="""
PART -1===================================================================================
Topics to be covered in today's class:
--> Introduction to Dictionaries
--> Creating Dictionaries
--> Accessing Values from dictionaries
--> Modifying Dictionaries (Adding or Updating Key-Value Pairs)
--> Deleting key:value pairs from Dictionaries
--> Merging Dictionaries
"""
abc = [2, 4.5, "rahi", 99, "reddy"]
""" #1. Introduction to Dictionaries
str datatype/ Data structure --> "characters"
list datatype / Data structure --> [elements]
tuple datatype / Data structure --> (elements)
set datatype / Data structure --> {elements}
dictionary datatype/ Data structure --> {item/s} item ==> key:value pair
Dictionary is a data structure that stores the value in key value pair {age: 32, qualification: "M.tech"}
(or)
Dictionary is an unordered, mapping from
unique immutable key to mutable/Immutable values
Syntax: {key1: value1, key2: value2, ...}
Methods : 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values' """
'''No duplicate key is allowed in dictionaries.
When duplicate keys encountered during assignment, the last assignment wins'''
basic_pay = 25000
basic_pay = 27000 # if we print basic_pay, it will display the latest value,same thing will happen in dictionary also
d = {'Name': 'NARENDRA', 'Age': 56, 'Role': 'farmer', 'Name': 'Udaya Bhaskara rao'}
# print(len(d)) # gives 3 (items) only because dictionary will not allow duplicate keys
# print(d)
""" Creating Dictionaries ---> (2 ways)
Create Empty Dictionary ---> (2 ways)
Create Dictionary with Data"""
# my_dict_1 = {} # Empty Dictionary creation
# print(my_dict_1, type(my_dict_1))
# my_dict_2 = dict() # Empty Dictionary creation
# print(my_dict_2, type(my_dict_1))
# Dictionary with Data
my_dict = {"name": "Narendra", "age": 33, 1990: (1, "Narendra", 44.5, 33, 55.5, 7),
"input_data":[22, 44, "Surendra", "LakshyaSree"],
"city": "New York"}
# print(my_dict,"\nLength of dictionary is :", len(my_dict))
""" # Accessing Values from dictionaries (2 ways)
# 1. Using Key --> Syntax : variable = instance/object[key]
Note: If key is not available interpreter will give KeyError
# 2. Using get() Method --> Syntax : variable = instance/object.get(key,[optional string])
get() method returns a value for the given key.
Note: If key is not available then returns default value None """
# output = my_dict["name"] # Using Key
# print(output) # Output: Narendra
#
# salary = my_dict["salary"] # Using Key
# print(salary) # Output: KeyError: 'salary' (if key is not available interpreter will give KeyError)
"""
Note: If you use get(key) method if key available, value will display on console,
if key Not available , None will display on console,
In this case, for get() method, we can pass Required string as 2nd optional argument """
my_dict = {"name": "Narendra", "age": 33, 1990: (1, "Narendra", 44.5, 33, 55.5, 7),
"input_data":[22, 44, "Surendra", "LakshyaSree"],
"city": "New York"}
# age = my_dict.get("Nanditha") # Using get Method
# print(age) # Output: 33
#
# abc = my_dict["Nanditha"]
# print(abc)
salary = my_dict.get("salary")
# print(salary) # Output: None
# salary = my_dict.get("input_data", "given Key is Not available")
# print(salary) # Output: "Not available" if the key doesn't exist
naren_dict = {'Name': 'NARENDRA', 'Age': 33, 'Designation': 'Module Lead'}
""" 4. Modifying Dictionaries:
--> Adding new Key-Value Pair to the dictionary
--> Updating existing Key-Value Pair """
""" Adding new Key-Value Pair to the dictionary """
# naren_dict["Qualification"] = "M.Tech" # Adding new Key-Value Pair
# print(naren_dict)
# naren_dict["reddy"] = 20
# print(naren_dict)
# naren_dict["Designation"] = "Technical Lead" # Updating existing Key-Value Pair
# print(naren_dict)
# Setting a Default Value for a Key:
# naren_dict.setdefault("salary", 145000) # this is another way to add new key:value pair
# print(naren_dict) # Output: {'name': 'Charlie', 'email': 'charlie@example.com', 'age': 27}
#
# naren_dict.setdefault("salary", 164000) # this is another way to add new key:value pair
# print(naren_dict) # Output: {'name': 'Charlie', 'email': 'charlie@example.com', 'age': 27}
#
# naren_dict.setdefault("Emp ID", "HM0002162") # this is another way to add new key:value pair
# print(naren_dict) # Output: {'name': 'Charlie', 'email': 'charlie@example.com', 'age': 27}
""" 5. Deleting key:value pairs from Dictionaries
--> You can remove individual item(key:value) from dictionary
--> By using pop() we can remove item(key:value)
--> By usig popitem()
--> You can clear all items(key:value) from dictionary """
# jaya = [33, 6.7, "aruna"]
# del jaya[1]
# print(jaya)
naren_dict = {'Name': 'NARENDRA', 'Age': 33, 'Designation': 'Team Lead', 'Qualification': 'M.Tech', 'salary': 145000}
# del naren_dict['Age'] # remove 'Age' key automatically value will be deleted
# print(naren_dict)
""" By using pop() we can remove item(key:value) """
# removed_value = naren_dict.pop("Qualification")
# print(removed_value) #
# print(naren_dict) # Updated dictionary
my_dict = {"a": 1, "b": 2, "c": 3} # Creating a dictionary
# Removing the last item
# last_item = my_dict.popitem()
# print(last_item) # Output: ('c', 3)
# print(my_dict) # Print the updated dictionary
# Output: {'a': 1, 'b': 2}
naren_dict = {'Name': 'NARENDRA', 'Age': 33, 'Designation': 'Team Lead', 'Qualification': 'M.Tech', 'salary': 145000}
# naren_dict.clear() # removing all items from dictionary
# print(naren_dict) # will print empty dictionary
"""6. Merging Dictionaries (Using update() Method:)'"""
my_dict = {"Institute": "BR Teschno Solutions", "Established Year": 2019, 'mobile': '9700422902'}
another_dict = {"email": "brtechnosolutions2019@gmail.com", "courses":["Python", "Testing", "MuleSoft", "DevOps"], "mobile":"9000 30 1444"}
# my_dict.update(another_dict)
# print(my_dict)
"""Note: we can't concatenate 2 dictionaries like list/tuple/strings by using + operator
if you try to add 2 dictionaries using + operate it will give
TypeError: unsupported operand type(s) for +: 'dict' and 'dict"""
# student1 = {"name": "Srikanth", "age": 25}
# student2 = {"name": "Meera", "age": 22}
# dict_3 = student1 + student2
# print(dict_3) # TypeError: unsupported operand type(s) for +: 'dict' and 'dict"""
"""constructors"""
# int() --> input is float value --> then it will convert into Integer value
# float() --> input is int value --> then it will convert into float value
# list() --> input is tuple --> then it will convert into list
# --> input is set --> then it will convert into list
# tuple() --> input is list --> then it will convert into tuple
# --> input is set --> then it will convert into tuple
# dict() --> input is list(tuples) --> then it will convert into dictionary
# --> input is list(lists) --> then it will convert into dictionary
# --> input is or tuple(tuples) --> then it will convert into dictionary
""" Creating a Dictionary from Two Lists using zip() method:
'list of tuples' or 'tuple of tuples' can be converted as dictionary using 'dict() method """
input = [("swetha","M.tech"),("NARENDRA", 1990), ("Bhagyasree", 1979), ("ravi", 1991)]
output = dict(input) # {'swetha': 'M.tech', 'NARENDRA': 1990, 'Bhagyasree': 1979, 'ravi': 1991}
# print(output)
input = [["swetha","M.tech"],["NARENDRA", 1990], ["Bhagyasree", 1979], ["ravi", 1991]]
output = dict(input) # {'swetha': 'M.tech', 'NARENDRA': 1990, 'Bhagyasree': 1979, 'ravi': 1991}
# print(output)
input = (("swetha","M.tech"),("NARENDRA", 1990), ("Bhagyasree", 1979), ("ravi", 1991))
output = dict(input) # {'swetha': 'M.tech', 'NARENDRA': 1990, 'Bhagyasree': 1979, 'ravi': 1991}
# print(output)===================================================================================
PART -2===================================================================================__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
#-----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> Using zip with Dictionaries
--> Sorting Dictionaries (by keys & by values)
--> Copying Dictionaries
--> fromkeys() method
--> keys(), values(), items()
--> Membership operators in dictionaries
--> Accessing required info from dictionary
--> Nested Dictionaries
--> list of dictionaries
--> tuple of dictionaries """
list_1 = ['NARENDRA', 'SURENDRA', 'Sravya',"Chandra"]
list_2 = [33, 28, 24, 44, 66, 55]
# zip_obj = zip(list_1, list_2) # (converting 2 lists into "list of tuples" object)
# print(zip_obj) # it provides the zip object
# list_of_tuple = list(zip_obj) # converting object to list
# print(list_of_tuple) # No need to print this
# print(dict(list_of_tuple)) # if you pass list of tuples to the dict() method, it will convert as dictionary
# print(dict(zip(list_1, list_2)))
list_1 = ['NARENDRA', 'SURENDRA', 'Sravya', "Chandra", "Manasa", "Niktha", "Jaya"]
list_2 = [27, 28, 24, 44, 66, 55]
# zip_obj = zip(list_1, list_2) # (converting 2 lists into "list of tuples" object)
# tuple_of_tuple = tuple(zip_obj)
# print(tuple_of_tuple) # No need to print this,
# print(dict(tuple_of_tuple))
# print(dict(list(zip(list_1, list_2)))) # directly converting 2 lists into dictionary in single line
# print(dict(tuple(zip(list_1, list_2)))) # directly converting 2 lists into dictionary in single line
# print(dict(zip(list_1, list_2))) # Realtime we will use this line for converting 2 lists into dictionary
""" # Copying Dictionaries ()
--> using copy() method
--> "dict()" constructor can also be used to copy dictionaries """
my_dict_1 = {"Institute": "BR Techno Solutions", "Established Year": 2019, 'mobile': '9000 30 1444'}
# print(my_dict_1)
my_dict_2 = my_dict_1 # shallow copy --> both dictionaries uses same memory location
# print(my_dict_2)
# print(id(my_dict_1), id(my_dict_2)) # Gives Same memory locations
my_dict_2["ganesh"] = 22 # I am performing modification in 2nd dictionary only
# print(my_dict_2)
# print(my_dict_1) # even user made chages in 2nd dictionary, due to shallow copy (they used same memory location) chnages will impact both dictionaries
# my_dict_1 = {"Institute": "BR Techno Solutions", "Established Year": 2019, 'mobile': '9000 30 1444'}
# my_dict_3 = my_dict_1.copy() # deep copy --> memory will be created separately for the new dictionary Ex: my_dict_3
# print(my_dict_3)
# print(id(my_dict_1), id(my_dict_3)) # Gives different memory locations
# my_dict_3["Kruthika"] = 22 # I am performing modification in 2nd dictionary only
# print(my_dict_3)
# print(my_dict_1)
my_dict_1 = {"Institute": "BR Techno Solutions", "Established Year": 2019, 'mobile': '9000 30 1444'}
# my_dict_4 = dict(my_dict_1) # by using dict() method we can perform deep copy
# print(my_dict_4)
# print(id(my_dict_1), id(my_dict_4)) # Gives different memory locations
# my_dict_4["jaya"] = 22 # I am performing modification in 2nd dictionary only
# print(my_dict_4)
# print(my_dict_1)
"""# fromkeys() method
--> Creating a dictionary with default value None
--> Creating a dictionary with a specified value for all keys
Syntax: d.fromkeys(seq,val)
"""
# Creating a dictionary with default value None
# keys = ["temparature", "humidity", "c","jaya", "varun"]
# new_dict = dict.fromkeys(keys)
# print(new_dict) # Output: {'a': None, 'b': None, 'c': None}
# Creating a dictionary with a specified value for all keys :
# keys = ["sugar", "Milk", "Ghee", "soaps"]
# value = "MRP"
# new_dict = dict.fromkeys(keys, value)
# print(new_dict) # Output: {'sugar': 'MRP', 'Milk': 'MRP', 'Ghee': 'MRP', 'soaps': 'MRP'}
companies = ["Apple", "Google", "Microsoft", "Amazon", "Facebook"] # List of companies
# Initializing the stock prices dictionary
# stock_prices = dict.fromkeys(companies, 0.0)
# print(stock_prices) # Print the stock prices dictionary
# Output: {'Apple': 0.0, 'Google': 0.0, 'Microsoft': 0.0, 'Amazon': 0.0, 'Facebook': 0.0}
###################################################################
"""
keys() --> method returns a list of all the available keys in the dictionary
values() --> method returns a list of all the available values in the dictionary.
items() --> method returns a list of (key, value) tuple pairs
"""
contact = {"firstName": "Narendra",
"lastName": "Boyina",
"age": 27,
"salary": "xxxxxx",
"registered": True
}
# print(contact.keys()) # dict_keys(['firstName', 'lastName', 'age', 'salary', 'registered'])
# print(contact.values()) # dict_values(['Narendra', 'Boyina', 27, 'xxxxxx', True])
# print(contact.items()) # dict_items([('firstName', 'Narendra'), ('lastName', 'Boyina'), ('age', 27), ('salary', 'xxxxxx'), ('registered', True)])
# del contact["lastName"]
# print(contact)
""" # Membership operators in dictionaries """
contact = {
"firstName": "Narendra",
"lastName": "Boyina",
"age": 27,
"sex": "M",
"salary": "xxxxx",
"registered": True,
}
"""Test if a key exists in a dictionary (Use in operator to test weather a key exists or not"""
# print('salary' in contact) #Output: True#
# print('Boyina' in contact)
# print('age' not in contact) # Output: False
# print('sarwesh' not in contact) # Output: True
""" # Accessing required info from dictionary """
my_dict = {"name": ["Narendra", "Salma", "Babji", 1.5], "Age": (27, 28, 25), 1995: "Babjan",
"srinivas": [3, 44, 2], "priyanka": {'Name': 'NARENDRA', 'Age': 26, 'Status': 'Married'}}
# print(type(my_dict), len(my_dict))
# print(my_dict["name"])
# print(my_dict["name"][2])
# print(my_dict["name"][2][2])
# print(my_dict["Age"][2])
# print(my_dict[1995][0])
# print(my_dict["Narendra"][0])
# print(my_dict["Srinivas"][1])
# print(my_dict)
# print(my_dict["priyanka"]["Age"])
""" # dictionary of dictionaries (Nesting Dictionaries ) """
contacts = {"student1": {'name': 'Narendra', 'mobile': '9700422902', 'email': 'boyinanarendra1@gmail.com'},
"student2": {'name': 'Surendra', 'mobile': [2332333, '9959538530'], 'email': 'surendraboyina1@gmail.com'},
"student3": {'name': 'Yugesh', 'mobile': '9999900007', 'email': 'sivaramprasad.perumella@gmail.com'}
}
# print(contacts.keys())
# print(contacts.values())
# contacts["student2"]["mobile"][0] = "9000301444"
# print(contacts)
""" # list of dictionaries """
data = [
{'name': 'Narendra',
'mobile': '9700422902',
'email': ['boyinanarendra1@gmail.com', "Vinod", 'nandithagnandhu@gmail.com', "Hanumanth", "Harinath",
"Sudheer"]},
{'name': 'Surendra',
'mobile': '99595xx530',
'email': 'surendraboyina1@gmail.com'},
{'name': 'BR Techno Solutions',
'mobile': '9000 30 1444',
'email': 'brtechnosolutions2019@gmail.com'}
]
# print(data, '\n', type(data), len(data))
# print(data[2]["name"])
# print(data[0]["email"][2][:-4])
# end_index = data[0]["email"][2].index(".com")
# print(data[0]["email"][2][ : end_index])
""" # tuple of dictionaries """
tup_dict = (
{'name': 'Narendra',
'mobile': '9700422902',
'email': ['boyinanarendra1@gmail.com', "Vinod", 'boyina', "Hanumanth", "Harinath", "Sudheer"]},
{'name': 'Surendra',
'mobile': '99595xx530',
'email': 'surendraboyina1@gmail.com'},
{'name': 'BR Techno Solutions',
'mobile': '9000 30 1444',
'email': 'brtechnosolutions2019@gmail.com'}
)
# print(tup_dict, len(tup_dict))
# print(tup_dict[0]["email"][3])
# tup_dict[0] = 10 # TypeError: 'tuple' object does not support item assignment
# x = r"C:\Users\nanarend\Downloads\Python_classes_May_2025\Class_44_Mini_project_1\testing_info"
x = "C:\\Users\\nanarend\\Downloads\\Python_classes_May_2025\\Class_44_project_2\\testing_info"
# print(x)
y = "hello\\example\\test.txt"
# print(y)
"""
Note1: If the width value is Even number, Fill characters will be added 1st right-hand side then remaining at left-hand
Note2: If the width value is Odd number, Fill characters will be added 1st left-hand side then remaining at right-hand
"""
# print("nandhitha".center(10,"$"))
# print("1234567".center(8, 'q'))
# print("1234567".center(8," "))
# print("abcdef".center(9, '1'))
# print('xyz'.encode())
# print("Hello {0!r} and {0!s}".format('foo', 'bin'))
# print(ord("g") - ord("a"))
# print('The sum of {0:b} and {1:x} is {2:o}'.format(2, 10, 9))
# print("Hello {0[0]} & {0[1]} and {1} ".format(('Nanditha', 'Venkat'), "Raahi"))
# import string
# print(string.ascii_letters)
############## Practice programs #############
d1 = {"c": [11, 22, 33, 44], "x": [55, 66, 77, 88]}
d2 = {"a": [11, 22, 33, 44], "b": [55, 66, 77, 88]}
# print(d2)
# print(d2["b"])
# print(d2["a"][2])
# d1.update(d2) #adding 2 dictionaries
# print(d1)
# print(d2)
list_1 = ['NARENDRA', 'SURENDRA', 'Sravya',"Chandra", "Manasa","Niktha"]
list_2 = [27, 28, 24, 44, 66, 55]
zip_obj = zip(list_1, list_2) # (converting 2 lists into "list of tuples" object)
# tuple_of_tuple = tuple(zip_obj)
# print(tuple_of_tuple)
# list_of_tuple = list(zip_obj) # converting object to list
# print(list_of_tuple)
"""
Parameters of the sorted() Method : The sorted() method can accept up to 3 parameters:
iterable – the data to iterate over. It could be a tuple, list, or dictionary.
key – an optional value, the function that helps you to perform a custom sort operation.
reverse – another optional value. It helps you arrange the sorted data in ascending or descending order
"""
# Sorting Dictionaries by Keys:
# cricket_players = {"Surya": 199, "Hardik": 144, "Rohit": 257, "Jadeja": 35, "Arshadeep": 12, "Virat": 151, "Siraj": 7}
# sorted_cricket_players_by_keys = dict(sorted(cricket_players.items()))
# print(sorted_cricket_players_by_keys)
# Output:{'Arshadeep': 12, 'Hardik': 144, 'Jadeja': 35, 'Rohit': 257, 'Siraj': 7, 'Surya': 199, 'Virat': 151}
# Sorting Dictionaries by values:
"""Right now you can't understand this program. Reason: you have to understood concept called lambda function,
I have kept this concept explanation in upcoming class, then i will explain "Sorting Dictionaries by values"
Reference: https://www.freecodecamp.org/news/sort-dictionary-by-value-in-python/
"""
# cricket_players = {"Surya": 199, "Hardik": 144, "Rohit": 257, "Jadeja": 35, "Arshadeep": 12, "Virat": 151, "Siraj": 7}
# sorted_cricket_players_score = dict(sorted(cricket_players.items(), key=lambda x:x[1]))
# print(sorted_cricket_players_score)
# output: [('Siraj', 7), ('Arshadeep', 12), ('Jadeja', 35), ('Hardik', 144), ('Virat', 151), ('Surya', 199), ('Rohit', 257)]
Author: Boyina Narendra
Supporting Author: M. Meera Sindhu
Request: If you find this information useful, please provide your valuable comments
No comments:
Post a Comment