0% found this document useful (0 votes)
54 views4 pages

Dictionary Notes

1. The document discusses various operations that can be performed on dictionaries in Python such as creating, accessing, modifying, deleting, sorting, and nesting dictionaries. 2. It provides code examples to demonstrate how to create dictionaries with single and multiple key-value pairs, access values using keys, loop through keys and values, add new items, replace and delete keys, and sort values within a dictionary. 3. Nested dictionaries are also created to store student details with subject scores within the nested values.

Uploaded by

Ilakkiyaa KP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views4 pages

Dictionary Notes

1. The document discusses various operations that can be performed on dictionaries in Python such as creating, accessing, modifying, deleting, sorting, and nesting dictionaries. 2. It provides code examples to demonstrate how to create dictionaries with single and multiple key-value pairs, access values using keys, loop through keys and values, add new items, replace and delete keys, and sort values within a dictionary. 3. Nested dictionaries are also created to store student details with subject scores within the nested values.

Uploaded by

Ilakkiyaa KP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

CREATING & ACCESSING:

In [1]: dict1={}
print(dict1,type(dict1),"Length of dict1 is: ", len(dict1))

{} <class 'dict'> Length of dict1 is: 0

In [2]: #d_name={key : value}


dict1={'Roll No' : 101}
#Accessing dict value: d_name[key]
print(dict1['Roll No'])

101

In [3]: #create dictionary with multiple key value pairs


dict_mul={'E_ID ' : 'IT101', ' E_Name ' : 'Priya', ' DPMT ' : ' IT ', 'PLACE' : ' TCR '}
print(dict_mul)

{'E_ID ': 'IT101', ' E_Name ': 'Priya', ' DPMT ': ' IT ', 'PLACE': ' TCR '}

NESTED DICTIONARY:

In [5]: students={'abc':{'CS':90,'DS':100,'DBMS':89},
'xyz':{'CS':45,'DS':70,'DBMS':77},
'mno':{'CS':99,'DS':86,'DBMS':98},
'pqr':{'CS':97,'DS':70,'DBMS':59},
'dfg':{'CS':69,'DS':65,'DBMS':67},}
for key,val in students.items():
print(key,val)

abc {'CS': 90, 'DS': 100, 'DBMS': 89}

xyz {'CS': 45, 'DS': 70, 'DBMS': 77}

mno {'CS': 99, 'DS': 86, 'DBMS': 98}

pqr {'CS': 97, 'DS': 70, 'DBMS': 59}

dfg {'CS': 69, 'DS': 65, 'DBMS': 67}

LOOPING:

In [4]: dict_mul={'E_ID ' : 'IT101', ' E_Name ' : 'Priya', ' DPMT ' : ' IT ', 'PLACE' : ' TCR '}
print("********KEYS**********")
for key in dict_mul:
print(key,end=' ')
print("\n********VALUES********")
for val in dict_mul.values():
print(val,end=' ')
print("\n******DICTIONARY******")
for key,val in dict_mul.items():
print(key,val,"\t",end=' ')

********KEYS**********

E_ID E_Name DPMT PLACE

********VALUES********

IT101 Priya IT TCR

******DICTIONARY******

E_ID IT101 E_Name Priya DPMT IT PLACE TCR

#### ADDING ITEMS:


In [4]: n = int(input("ENTER NO. OF ITEMS TO BE ADDED :"))
d = {}
for i in range(n):
keys = input("Enter key : ") # here i have taken keys as strings
values = input(" Enter Value: ") # here i have taken values as integers
d[keys] = values
print(d)

ENTER NO. OF ITEMS TO BE ADDED :3

Enter key : ID

Enter Value: 101

Enter key : NAME

Enter Value: PRIYA

Enter key : DPMT

Enter Value: IT

{'ID': '101', 'NAME': 'PRIYA', 'DPMT': 'IT'}

In [5]: # Python code to demonstrate a dictionary


# with multiple inputs in a key.
import random as rn
# creating an empty dictionary
dict = {}
# Insert first triplet in dictionary
x, y, z = 10, 20, 30
dict[x, y, z] = x + y - z;
# Insert second triplet in dictionary
x, y, z = 5, 2, 4
dict[x, y, z] = x + y - z;
# print the dictionary
print(dict)
print(dict[5,2,4])

{(10, 20, 30): 0, (5, 2, 4): 3}

MODIFYING:

In [6]: # REPLACE KEY


dd={'nikhil': 1, 'vashu' : 5,
'manjeet' : 10, 'akshat' : 15}
print ("initial 1st dictionary", dd)
a=input("Enter key to find:")
for aa in dd:
if(a==aa):
print("Values of given key is :",dd[a])
x=input("Enter key to replace:")
dd[x]=dd[aa]
del dd[aa]
print(dd)
break
else:
print("Not present")

initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}

Enter key to find:akshat

Values of given key is : 15

Enter key to replace:akshay

{'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshay': 15}

In [7]: # INSERTING ITEMS


dict = {'key1':'geeks', 'key2':'for'}
print("Current Dict is: ", dict)
# adding key3
dict.update({'key3':'geeks'})
print("Updated Dict is: ", dict)
# adding dict1 (key4 and key5) to dict
dict1 = {'key4':'is', 'key5':'fabulous'}
dict.update(dict1)
print(dict)
# by assigning
dict.update(newkey1 ='portal')
print(dict)

Current Dict is: {'key1': 'geeks', 'key2': 'for'}

Updated Dict is: {'key1': 'geeks', 'key2': 'for', 'key3': 'geeks'}

{'key1': 'geeks', 'key2': 'for', 'key3': 'geeks', 'key4': 'is', 'key5': 'fabulous'}

{'key1': 'geeks', 'key2': 'for', 'key3': 'geeks', 'key4': 'is', 'key5': 'fabulous', 'newkey
1': 'portal'}

DELETING:

In [9]: # Python3 code to demonstrate working of


# Remove Keys from dictionary starting with K
# Using Naive Method + startswith() + pop()

# initializing dictionary
test_dict = {"Apple" : 1, "Star" : 2, "App" : 4, "Gfg" : 3}

# printing original dictionary
print("The original dictionary is : " + str(test_dict))

# initializing Substring
K = "Ap"
# Using Naive Method + startswith() + pop()
# Remove Keys from dictionary starting with K
res = list(test_dict.keys())
for key in res:
if key.startswith(K):
test_dict.pop(key)

# printing result
print("Dictionary after key removal : " + str(test_dict))

The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}

Dictionary after key removal : {'Star': 2, 'Gfg': 3}

SORTING:
In [8]: # Python program to sort the list
# alphabetically in a dictionary
dict ={
"L1":["Geeks", "for", "Geeks"],
"L2":["A", "computer", "science"],
"L3":["portal", "for", "geeks"],
}
print("\nBefore Sorting: ")
for x in dict.items():
print(x)
print("\nAfter Sorting: ")
for i, j in dict.items():
sorted_dict ={i:sorted(j)}
print(sorted_dict)

Before Sorting:

('L1', ['Geeks', 'for', 'Geeks'])

('L2', ['A', 'computer', 'science'])

('L3', ['portal', 'for', 'geeks'])

After Sorting:

{'L1': ['Geeks', 'Geeks', 'for']}

{'L2': ['A', 'computer', 'science']}

{'L3': ['for', 'geeks', 'portal']}

You might also like