Dictionaries In Python Example Practice

Contents show

Dictionaries In Python Example Programs

dictionaries in python example practice
dictionaries in python example practice

To read :- Python Dictionaries Tutorial

dictionaries in python example

This Python Dictionary example exercise aims to help python developers to learn and do practice of dictionary operations. Here I am providing 14 dictionary programs to help you in brushing up your coding skills.

All questions are tested on Python 3.

A dictionary object is mutable in Python. Python dictionary contains the data in the form of key-pairs.

Each key is separated from its value by colon(:).

Q 1. Write a program to create a phone dictionary for all your friends and then print it.

dictionaries in python example practice


Program.

PhoneDict = {"Madhav" : 1234567, "Steven" : 7654321, "Dilpreet" : 6734521, "Rabiya" : 4563217, "Murughan" : 3241567, "Sampree" : 4673215}
for name in PhoneDict :
      print(name, ":", PhoneDict[name])

The output produced by above program will be :


Rabiya : 4563217
Murughan : 3241567
Madhav : 1234567
Dilpreet : 6734521
Steven : 7654321
Sampree : 4673215

Q 2. A Dictionary contains details of two worker with their names as keys and other details in the form of dictionary as value. Write a program to print the worker’s information in records format.

Program.

Employees = {'john' : {'age' : 25, 'salary' : 20000}, 'Diya' : {'age' : 35, 'salary' : 50000}}
for key in Employees :
      print("Emloyee", key, ':')
      print('Age' : ', str( Employees[key]['age']))
      print('salary :', str(Employees[key]['salary']))

Q 3. Write a program to create a dictionary containing names of competition winner students as keys and number of their wins as values.

Program.

n = int(input("How many students ? "))
ComWinner = { }
for a in range(n) :
             key = input("Name of the student :")
             value = int(input("Number of competitions won :"))
             CompWinner[key] = value
print("The dictionary now is :")
print(CompWinner)

The sample run of above program is :


How many students ? 5
Name of the student : Rohan
Number of competitions won : 5
Name of the student : Zeba
Number of competitions won : 3
Name of the student : Nihar
Number of competitions won : 3
Name of the student : Roshan
Number of competitions won : 1
Name of the student : James
Number of competitions won : 5
The dictionary now is :
{‘Nihar’ : 3, ‘rohan’ : 5, ‘Zeba’ : 3, ‘Roshan’ : 1, ‘James’ : 5}

Q 4. Program to count the frequency of a list-elements using a dictionary.

import json
sentence = "This is a super idea This / idea will change the idea of learning"
words = sentence.split()
d = {}
for one in words :
       key = one
       if key not in d:
            count = words.count(key)
            d[key] = count
print("Counting frequencies in list/n", words)
print(json.dumps(d, indent = 1))

The output of program :

counting frequencies in list
[‘This’, ‘is’, ‘a’, ‘super’, ‘idea’, ‘This’, ‘idea’, ‘will’, ‘change’, ‘the’, ‘idea’, ‘of’, ‘learning’]
{
“This” : 2,
“is” : 1,
“a” : 1,
“super” : 1,
“idea”: 3,
“will” : 1
“change” : 1,
“the”: 1,
“of” : 1,
“learning” : 1
}

Q 5. Write a program that checks for presence of a value inside a dictionary and prints its key.

info = {'Riya' : 'CSc.', 'Mark' : 'Eco', 'Ishpreet' : 'Eng', 'Kamaal' : 'Env.Sc'}
inp = input("Enter value to be searched for :")
if inp in info.values() :
         for a in info:
               if info[a] == inp :
                      print("The key of given value is", a)
                      break
          else :
                print("Given value does not exist in dictionary")

Enter value to be searched for : Env.Sc

The key of given value is kamaal

====================================

Enter value to be searched for : eng
Given value does not exist in dictionary

Q 6. The code of previous will not work ifhte cases of the given value inside dictionary are different. That is, the result(of previous program) will be like:


Enter value to be searched for : eng
Given value does not exist in dictionary


Make changes in above program so tht the program returns the key, even if the cases differ, i.e., match the two values gnoring their cases

info = {'Riya' : 'CSc.', 'Mark' : 'Eco', 'Ishpreet' : 'Eng', 'Kamaal' : 'Env.Sc'}
inp = input("Enter value to be searched for :")
for a in info:
        if info[a].upper() == inp.upper() :
               print("The key of given value is", a)
               break
else :
       print("Given value does not exist in dictionary")

The sample run of above program is as given below :


Enter value to be searched for : eng
The key of given value is Ishpreet

Q 7. The membership operator only work with keys of a dictionary but to check for the presence of a value in a dictionary, you need to write a code.


Write a Python program that takes a value and checks whether the given value is part of given dictionary or not. If it is, it should print the corresponding key otherwise print an error message.

dict1 = {0 : "Zero", 1 : "One", 2 : "Two", 3 : "Three", 4 : "Four", 5 : "Five"}
ans = "y"
while ans == 'y' or ans == 'y' :
       val = input("Enter value:")
       print("value", val, end= " ")
       for k in dict1 :
             if dict1[k] == val :
                 print("exists at", k)
        else :
              print("not found")
ans = input("Want to check more values ? (y/n) :")

Q 8.Marks of three students “suniti”, “Ryna” and “Zeba” in three subjects are available in following three dictionaries respectively :
d1 = {1 : 40, 2 : 70, 3 : 70}
d2 = {1 : 40, 2 : 50, 3 : 60}
d3 = {1 : 70, 2 : 80, 3 : 90}


Create a nested dictionary that stores the marks details along with student names and then prints the output shown below :

Name 
Ryna
subject (key)             Marks (value)
       1                                40
       2                                50
       3                                60
Name 
Zeba
subject (key)             Marks (value)
       1                                70
       2                                80
       3                                90
Name 
Ryna
subject (key)             Marks (value)
       1                                40
       2                                70
       3                                70

ans.

d1 = {1 : 40, 2 : 70, 3 : 70}
d2 = {1 : 40, 2 : 50, 3 : 60}
d3 = {1 : 70, 2 : 80, 3 : 90}
d4 = {"Suniti" : d1, "Ryna" : d2, "Zeba" : d3}
for x in d4.keys() :
      print("Name")
      print(x)
      print("Subject(key)", '/t', "Marks(value)")
      for y in d4[x].keys():
               print(" ", y, '/t/t', d4[x][y])
       print()

Q 9. Consider a dictionary my_points with single-letter keys, each followed by a 2-element tuple representing the coordinates of a point in an x-y coordinate plane.


my_points = {‘a’ : (4, 3), ‘b’ : (1,2), ‘c’ : (5,1)}


Write a program to print the maximum value from within all of the values tuples at same index.


For example, maximum for 0th index will be computed from values 4, 1 and 5, i.e., all the entries at 0thindex in the value-tuple.
Print the result in following format :


Maximum Value at index(my_points, 0) = 5
Maximum Value at index(my_points, 1) = 3

ans.

my_points = {'a' : (4, 3), 'b' : (1,2), 'c' : (5,1)}
highest= [0, 0]
init = 0
for a in range92) :
    init = 0
    for b in my_points.keys():
          val = my_points[b][a]
          if init == 0 :
                   highest[a] = val
          init += 1
          if val > highest[a] :
                   highest[a] = val
print("Maximum Value at index(my_points, ", a, ") = ", highest[a])

Higher Order Thinking Programs

Of

Dictionaries In Python Example

Q 1. Q 1. Write a program that asks the user the day number in a year in the range 2 to 365 and asks the first day of the year – Sunday or Monday or Tuesday etc. Then the program should display the day on the day-number that has been input.

days =  {'Monday' : 0, 'Tuesday' : 1, 'Wednesday' : 2, 'Thusday' : 3, 'Friday' : 4, 'Saturday' : 5, 'Sunday' : 6}
n = int(input("Enter the day of the year :"))
added = (n-1)%7
first = input("First day of the year :")
while first not in days :
          print("Please enter a correct day with first letter capital, e.g. Monday")
          first = input("First day of the year :")
current_day = days[first] + added
for day in days :
      if days[day] == current_day :
          print(day)
          break

Q 2. Write a program that reads a date as an integer in the format MMDDYYYY. The program will call a function that prints print out the date in the format ,.
Sample run :
Enter date : 12252021
December 25, 2021

date = input("Enter date in MMDDYYYY format :")
def PrettyPrint(date) :
      months = {1 : 'January', 2 : 'February', 3 : 'March', 4 : 'April', 5 : 'May', 6 : 'June', 7 : 'July', 8 : 'August', 9 : 'September', 10 : 'October', 11 : 'November', 12 : 'December'}
      month = months[int(date[ : 2] ) ]
      day = date[2 : 4]
      year = date[4:]
      PrettyDate  = month + " " + day + ", " + year 
      print(PrettyDate)
PrettyPrint(date)

Q 3. Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It should return a new dictionary, with all the items in both its arguments (assumed to be dictionaries). If the same key appears in both arguments, feel free to pick a value from either.

def addDict(dict1, dict2) :
       newDict = { }
       for i in dict1 :
             newDict[i] = dicct[i]
       for i in dict2 :
             newDict[i] = dict2[i]
       return newDict

Q 4. Write a program to sort a dictionary’s keys using Bubble sort and produce the sorted keys as a list.

def bubbleSort(arr) :
      for i in range(len(arr) - 1) :
            for j in range(len(arr) - i - 1) :
                  if arr[j] > arr[ j + 1] :
                        arr[j], arr[j + 1] = arr[j + 1], arr[j]
      return arr
def sortDictkeys(dictionary) :
       return bubbleSort(dictionary.keys( ) )
def sortDictValues(dictionary) :
       return bubbleSort(list(dictionary.values( ) )

Read More :-

Python Dictionaries Tutorial

dictionary in python

Dictionary in Python class 11 notes

dictionaries in python notes

python dictionary practice problems

FAQ :-

dictionaries in python

Q 1. What are the dictionaries in Python?

ans.

Dictionaries in Python

Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array.

dictionary consists of a collection of key-value pairs.

Each key-value pair maps the key to its associated value.

Q 2. How do you create a dictionary in Python?

ans. To create a Python dictionary, we need to pass a sequence of items inside curly braces {} , and separate them using a comma (,). Each item has a key and a value expressed as a “key:value” pair. The values can belong to any data type and they can repeat, but the keys must remain unique.

Q 3. What is difference between list and dictionary?

ans. A list is an ordered sequence of objects, whereas dictionaries are unordered sets.

However, the main difference is that items in dictionaries are accessed via keys and not via their position.

The values of a dictionary can be any type of Python data. So, dictionaries are unordered key-value-pairs.

Q 4. Is a dictionary a list Python?

ans. Python provides another composite data type called a dictionary, which is similar to a list in that it is a collection of objects.

Q 5. What is the difference between Array and dictionary?

ans. An array is just a sorted list of objects.

dictionary stores key-value pairs.

There are no advantages or disadvantages, they are just two data structures, and you use the one you need.

The key difference is how you can access within them.

Q 6. How do you declare a dictionary in python?

ans. A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces({}). Python Dictionary is classified into two elements: Keys and Values. Values can be a list or list within a list, numbers, etc.

Q 7. Are Dictionaries ordered Python?

ans. Dictionaries are ordered in Python 3.6 (under the C Python implementation at least) unlike in previous incarnations.

Q 8. How do you create a dictionary?

ans. On a separate piece of paper, organize your words so that they’ll be easier to find. Organize them by the first letter of the word, then the second, then the third, etc. Edit your rough draft. To ensure that you have a good dictionary, go through your paper and correct any mistakes.

Q 9. Is dict a keyword in Python?

ans.

Python dict() Syntax

kwarg: It’s a keyword argument and is optional in the function. **kwarg let you take an arbitrary number of keyword arguments. mapping: It is also optional (Another dictionary).

Q 10. Can a dictionary key be a list Python?

ans. Newcomers to Python often wonder why, while the language includes both a tuple and a list type, tuples are usable as a dictionary keys, while lists are not. This was a deliberate design decision, and can best be explained by first understanding how Python dictionaries work.