Skip to main content

GRADE XI - PYTHON DICTIONARY - 06-11-2024

 GRADE XI 

PYTHON DICTIONARY

Python Dictionary is collection of elements where each element is a key-value pair.

#CREATE DICTIONARY

d={}    #EMPTY DICTIONARY

print(d)

#print(type(d))     #type of data


#METHOD TO CREATE DICTIONARY

dict= {} or d1 = dict()


dict1={'mihir':'gurgaon','Agastya':'delhi','Palak':'GGN'}

print(dict1)


#insert data in Empty Dictionary

D1={}

D1[1]="ONE"

D1[2]="TWO"

D1[3]="THREE"

D1[4]="FOUR"

print(D1)

#APENDING VALUES IN DICT

dict1={'R':'Rain','B':'Ball','C':'Cat','T':'Tree','Age':15}

dict1['Name']='Preeti'

print(dict1)


#UPDATING ELEMENTS IN A DICTIONARY

dict1={'R':'Rain','B':'Ball','C':'Cat','T':'Tree','Age':15}

dict1['Name']="RIYA"

print(dict1)

#TRAVERSING A DICTIONARY

dict1={'R':'Rain','B':'Ball','C':'Cat','T':'Tree','Age':15}

for i in dict1:

    print(i,':',dict1[i])

# COMMON DICTIONARY FUNCTIONS AND METHODS

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

res=len(A)

print(res)


#clear function - it removes all the items from the dictionary

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

A.clear()

print(A)


#get() - Returns the value for given key

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

res=A.get('Wed')

print(res)


#items() - returns the content of dictionary

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

res=A.items()

print(res)


#key()- It return list of key values in a dictionary

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

res=A.keys()

print(res)


#Values() - returns a list of values from key-value pairs in a dictionary

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

res=A.values()

print(res)


#REMOVING AN ITEM FROM DICTIOARY

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

del A['Wed']

print(A)


#If Particular Key is not there , it will result in error

#A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

#del A['Fri']

#print(A)


#Remove Item using pop(key)

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

A.pop('Wed')

print(A)


#IN AND NOT IN MEMBERSHIP OPERATOR

A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

res='Thu' in A

print(res)


A={"Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday"}

res='Mon' not in A

print(res)

print("😎\n" *5)

#Try to copy any emoji you wish

#(https://tools.picsart.com/text/emojis/) and build your own pattern

print(''.join("😉" *5))

print('\n'.join("😉" *5))

n = 5

print('\n'.join("😉" * i for i in range(1, n + 1)))

print("😉\n" +"💢" )

PRACTICE QUESTIONS

1. #CREATE A DICT WHICH STORES NAME AND PH NO OF YOUR FRIENDS(ANY 5)

#AND DISPLAY THE NAMES AND PH_NO IN THE DICTIONARY.

Sol:

phdict={"Kavya":2345,"Agastya":5667,"Mihir":7890,"Palak":6544,"Sanya":555}

for name in phdict:

    print(name,":",phdict[name])

2.#WAP to create a dictionary of two workers and their names as keys and other details in the form 

of values

Sol:

employee={'Riya':{'age':25,'Salary':20000},'Divya':{'age':35,'Salary':50000}} 

for key in employee:

    print("Employee",key,":")

    print("Age:",employee[key]['age'])

    print("Salary:",employee[key]['Salary'])


3.WAP to create a dictionary containing names of competition winner students as KEY and number of their wins as values

Sol:

n=int(input("How Many Students ?")) 

compwinner={ }

for i in range(n):

    key=input("Enter Name of the Student:")

    value=int(input("Enter No of Wins:"))

    compwinner[key]=value

print("The Dictionary is:", compwinner)


4.#WAP TO INPUT TOTAL NO OF SECTIONS AND STREAM IN 11TH CLASS AND DISPLAY ALL

Sol:

5.WAP to create a dictionary containing roll number of students and percentage as values for n number of students display the total number of students scoring more than 80

Sol:

stud={ }# Empty dictionary created

n=int(input("enter number of students - "))

for i in range(n):

       rno = input("enter Roll No - ")

      stud[rno] = float(input("Enter percentage –"))


ctr=0

for rno in stud:

    if stud[rno]>80:

        ctr+=1

print("No. of students scoring percentage above 80 –" ,ctr)

6.#Program to create a dictionary which stores names(key) of employees and their salary(value)


7.Write a program to create a dictionary a key:valuepair for “n” number of elements . Check and display whether the dictionary with different keys have same values or not. Display appropriate message.

Sol:

d1 = {}

n = int(input("Enter number of elements: "))


# Input keys and values

for i in range(n):

    key = int(input("Enter key: "))

    d1[key] = eval(input("Enter value: "))


# Check for duplicate values

found_duplicate = False

for k in d1: #iterates over each key in the dictionary

    cnt = 0

    for k1 in d1:            # iterates over all the keys in the dictionary again, checking if the value     

                                       associated with key k  

        if d1[k] == d1[k1]:

            cnt += 1

        if cnt > 1:

            break

    if cnt > 1:

        found_duplicate = True

        print("Keys have the same value")

        break

if not found_duplicate:

    print("No keys have the same value")

8.WAP TO INPUT NAMES(KEY) OF 'N' COUNTRIES AND THEIR CAPITAL AND CURRENCY(VALUES) STORE IT IN A DICTIONARY. ALSO SEARCH AND DISPLAY A PARTICULAR COUNTRY

dict={}    

n=int(int(input("Enter Number of countries")))

for i in range(n):

    cname=input("Enter country name")

    cap=input("Enter Capital name")

    curr=input("Enter Currency")

    dict[cname]=[cap,curr]   #Value as list assigned

sname=input("Enter country name to search")

for cn in dict:

    if cn==sname:

        print("Name found in dictionary")

        print("details of",cn,"-",dict[cn])

        break

    else:

        print("Country name not found")

Comments

Popular posts from this blog

GRADE XII - Python Connectivity with MySQL

  Python Connectivity with MySQL In real-life applications, the data inputted by the user and processed by the application needs to be saved permanently, so that it can be used for future manipulation. Usually, input and output data is displayed during execution but not stored, as it resides in main memory , which is temporary — i.e., it gets erased once the application is closed. This limitation can be overcome by sending the data to be stored in a database , which is made accessible to the user through a Front-End interface . Key Concepts Database A database is an organized collection of data that is stored and accessed electronically from a computer system. DBMS (Database Management System) A DBMS is software that interacts with end-users, applications, and the database to capture and analyze data. Front-End The Front-End is the user interface of the application, responsible for input/output interaction with the user. Back-End The Back-End refe...

GRADE XII - CSV FILE

CSV FILE (COMMA SEPERATED VALUE) CSV NOTES LINK :  CSV NOTES - CLICK HERE Writing data to a CSV file involves the following steps: Import the csv module Open the CSV file in write mode ( "w" ) using open() Create the writer object Write the data into the file using the writer object Close the file using close() writerow() Method This method is used to write a single row to a CSV file. It takes a sequence (list or tuple) as its parameter, and writes the items as a comma-separated line in the file. You do not need to add a newline character (\n) — it automatically places the end-of-line marker.     EXAMPLE 1: import csv  # Importing the csv module # CSV file opened using relative path csv_fobj = open("emp.csv", "w")   # Writer object created wtr_obj = csv.writer(csv_fobj) # Record with field heading is written wtr_obj.writerow(["Empno", "Name", "Salary"]) # Records with data are...