Online Courses
Free Tutorials  Go to Your University  Placement Preparation 
Goeduhub's Online Courses @ Udemy in Just INR 570/-
Online Training - Youtube Live Class Link
2 like 5 dislike
7.4k views
in Python Programming by Goeduhub's Expert (2.2k points)

Assignment/Task 3

Question on Dictionary-

Q.1 Write a Python Program to sort (ascending and descending) a dictionary by value. 

Q.2 Write a Python Program to add a key to a dictionary. 

Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30}

Q.3 Write a  program asks for City name and Temperature and builds a dictionary using that Later on you can input City name and it will tell you the Temperature of that City.

Q. 4 Write a Python program to convert list to list of dictionaries.

Sample lists: ["Black", "Red", "Maroon", "Yellow"], ["#000000", "#FF0000", "#800000", "#FFFF00"]

Expected Output: [{'color_name': 'Black', 'color_code': '#000000'}, {'color_name': 'Red', 'color_code': '#FF0000'}, {'color_name': 'Maroon', 'color_code': '#800000'}, {'color_name': 'Yellow', 'color_code': '#FFFF00'}]

 Q. 5 We have following information on Employees and their Salary (Salary is in lakhs),

Employee Salary
John 14
Smith 13
Alice 32
Daneil 21
  1. Using above create a dictionary of Employees and their Salary
  2. Write a program that asks user for three type of inputs,
    1. print: if user enter print then it should print all Employees with their Salary in this format,
      1. John ==>14
      2. Smith ==>13
      3. Alice ==>32
      4.  Daneil ==>21
    2. add: if user input adds then it should further ask for an Employee name to add. If Employee already exists in our dataset then it should print that it exists and do nothing. If it doesn't then it asks for Salary and add that new Employee/Salary in our dictionary and print it
    3. remove: when user inputs remove it should ask for an Employee to remove. If an Employee exists in our dictionary then remove it and print a new dictionary using format shown above in (a). Else print that Employee doesn't exist!
    4. query: on this again ask the user for which Employee he or she wants to query. When a user inputs that Employee it will print the Salary of that Employee.

     Questions on Sets-

     Q.1 What is the difference between a set and a frozenset? Create any set and try to use frozenset(setname).

    Q.2 Find the elements in a given set that are not in another set

        set1 = {10,20,30,40,50}

        set2 = {40,50,60,70,80}

     Difference between set1 and set2 is {10,20,30}

    Goeduhub's Top Online Courses @Udemy

    For Indian Students- INR 360/- || For International Students- $9.99/-

    S.No.

    Course Name

     Coupon

    1.

    Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence

    Apply Coupon

    2.

    Natural Language Processing-NLP with Deep Learning in Python Apply Coupon

    3.

    Computer Vision OpenCV Python | YOLO| Deep Learning in Colab Apply Coupon
        More Courses

    7 Answers

    0 like 0 dislike
    by (342 points)
    selected by
     
    Best answer
    1 Write a Python Program to sort (ascending and descending) a dictionary by value. 
    import operator
    x = {'A':5,'B':4,'C':2,'D':6,'E':3}
    asc = sorted(x.items(), key=operator.itemgetter(1))
    print('Ascending Order Is : ',asc)
    desc = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
    print('Descending Order Is : ',desc)
    2 Write a Python Program to add a key to a dictionary. 
    x = {'A':5,'B':4,'C':2,'D':6,'E':3}
    x.update({'E':8})
    x
    3 Write a  program asks for City name and Temperature and builds a dictionary using that Later on you can input City name and it will tell you the Temperature of that City.
    dic = dict()
    n = int(input('Enter The Number Of Cities : '))
    for i in range(n):
      city = input('Enter A Name Of The City : ')
      temp = int(input('Enter The Temperature In Celcious Of The City : '))
      dic[city] = temp
    print('Created Dictionary Is : ',dic)
    city_name = input('Enter Name Of The City To Check Temperature Of It : ')
    print('Temperature Of The City Is : ',dic[city_name])
    4.Write a Python program to convert list to list of dictionaries.
    list1 = ["Sathya","Yuvi","Sathish","Vignesh","Prakash",]
    list2 = [23,26,24,22,23]
    print([{'Name': f, 'Age': c} for f, c in zip(list1, list2)])
    5 We have following information on Employees and their Salary (Salary is in lakhs),
    data = {'John':1400000'Smith':1300000'Alice':3200000'Daniel':3200000}
    print('Data Of Employee And Their Salaries')
    user_input = input('What Do You Want With This Data (Print\Add\Remove\Query) : '.title())
    if user_input=='Print':
      for i in data.items():
        print(i[0],'==>',i[1])
    elif user_input == 'Add':
      new_name = input('Enter A Name Of New Employee : ')
      if new_name in data.keys():
        print('This Name Is Already In Data')
      else:
        new_sal = int(input('Enter The Salary Of Employee : '))
        data[new_name]=new_sal
        for j in data.items():
          print(j[0],'==>',j[1])
    elif user_input == 'Remove':
      rem = input('Enter A Employee Name To Remove : ')
      if rem in data:
        del data[rem]
        for k in data.items():
          print(k[0],'==>',k[1])
      else:
        print('Employee Does Not Exist')
    elif user_input == 'Query':
      quer = input('Enter The Name Of The Employee Wants To Query')
      if quer in data:
        print(data[quer])
      else:
        print('The Name Does Not Exist')
    else:
      print('Enter Only Valid Input')
    What is the difference between a set and a frozenset? Create any set and try to use frozenset(setname).
    The frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Set Is Mutable.
    vowels = ('a''e''i''o''u')
    fSet = frozenset(vowels)
    print('The frozen set is:', fSet)
    print('The empty frozen set is:', frozenset())
    fSet.add('v')
    What is the difference between a set and a frozenset? Create any set and try to use frozenset(setname).
    set1 = {10,20,30,40,50}
    set2 = {40,50,60,70,80}
    print(set1.difference(set2))
    0 like 0 dislike
    by (278 points)

    GO_STP_6266

    https://www.linkedin.com/posts/sahil-parmar-4099391bb_google-colaboratory-activity-6803657028238741504-V4RA

    0 like 0 dislike
    by (592 points)

    1) a = {1:2 ,2:1 ,4:3 ,3:4 ,6:5 ,5:6 }

    #this will print a sorted list of the keys

    print(sorted(a.values()))

    #this will print the sorted list with items.

    print(sorted(a.items()))

    2) d = {0:10, 1:20}

    print(d)

    d.update({2:30})

    print(d)

    3) name,temp = input("enter city name and temperature and enter 0 0 for discontinuing").split()

    t = {}

    t.update({name:int(temp)})

    while name and int(temp):

      name,temp = input("enter city name and temperature").split()

      t.update({name:int(temp)}) 

    name = input("enter city name")

    print(t[name])

    4)  test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]

    print("The original list : " + str(test_list))

    key_list = ["name", "number"]

      

    n = len(test_list)

    res = []

    for idx in range(0, n, 2):

        res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})

    print("The constructed dictionary list : " + str(res))

    5) vin = ['John','Smith','Alice','Daniel']

    kp = [14, 13, 32, 21]

    Dict = dict(zip(vin, kp))

    print(Dict)

    vin = ['John','Smith','Alice','Daniel']

    kp = [14, 13, 32, 21]

    inp= input("Enter your choice : print or add or remove or query: ")

    if inp == 'print':

        Dict = dict(zip(vin, kp))

        for a in Dict:

            print(a,"==>",Dict[f"{a}"])

    elif inp =='add':

        emp= input("Enter the name of the Employee to be added: ")

        if emp.title() in Dict.keys():

            print(f"{emp} name is already existing!")

        else:

            salr = input(f"Enter the salary of the {emp} ")

            Dict.update({emp : salr})

            print(Dict)

    elif inp == 'remove':

        name = input("Enter the name of the employee to be removed? ")

        if name in Dict:

            Dict.pop(name)

            print(Dict)

        else:

            print(f"Sorry!!, {name} doesn't exist in the data!")

    elif inp == 'query':

        emp= input("Enter the name of the employee you want to query: ").title()

        if emp in Dict.keys():

            print(f"The salary of {emp} is {Dict[emp]}")

        else:

            print(f"The employee named {emp} doesn't exist!!")

    else:

        print("Enter a valid choice")

    QUESTIONS ON SETS:-

    1) Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Due to this, frozen sets can be used as keys in Dictionary or as elements of another set.

    setname = (1, 2, 3, 4, 5, 6, 7, 8, 9)

    fnum = frozenset(setname)

    print("frozenset Object is : ", fnum)

    2) set1 = {10,20,30,40,50}

    set2 = {40,50,60,70,80}

    print("Original sets:")

    print(set1)

    print(set2)

    print("Difference of set1 and set2 using difference():")

    print(set1.difference(set2))

    0 like 0 dislike
    by (115 points)

    Q.1 Write a Python Program to sort (ascending and descending) a dictionary by value. 

    Ans:- import operator

            a={1:3,3:4,4:3,2:1,0:0}

            print('dictionary:',a)

            b=sorted(a.items(),key=operator.itemgetter(1))

            print('assemding order:',b)

            c=sorted(a.items(),key=operator.itemgetter(1),reverse=true)

            print('dessending order:',c)

    Q.2 Write a Python Program to add a key to a dictionary. 

    Sample Dictionary : {0: 10, 1: 20}
    Expected Result : {0: 10, 1: 20, 2: 30}

    Ans:-   a={0:10,1:20}

               a[2]=30

              print(a)

         O/P:-    {0:10,1:20,2:30}

    Q. 4 Write a Python program to convert list to list of dictionaries.

    Sample lists: ["Black", "Red", "Maroon", "Yellow"], ["#000000", "#FF0000", "#800000", "#FFFF00"]

    Expected Output: [{'color_name': 'Black', 'color_code': '#000000'}, {'color_name': 'Red', 'color_code': '#FF0000'}, {'color_name': 'Maroon', 'color_code': '#800000'}, {'color_name': 'Yellow', 'color_code': '#FFFF00'}]

    Ans:-  color_name= ["Black", "Red", "Maroon", "Yellow"]

              color_code= ["#000000", "#FF0000", "#800000", "#FFFF00"]

             print([{'color_name':n,'color_code':c for n,c in zip(color_name,color_code)

    Questions on Sets-

     Q.1 What is the difference between a set and a frozenset? Create any set and try to use frozenset(setname).

    Ans:- A set ia mutable and frozenset is immutable. we can not add or remove in frozenset once it is created.

           set={"mumbai","delhi","chennai"}

           a=frozenset(set)

          print(set)

         b=a.add(banglore)

        print(b)

       O/P:-   'frozenset' object has no attribute 'add'

    Q.2 Find the elements in a given set that are not in another set

        set1 = {10,20,30,40,50}

        set2 = {40,50,60,70,80}

    Ans:-    set1={10,20,30,40,50}

                set2 = {40,50,60,70,80}

                a= set1.difference(set2)

                print(a)

          O/P:-    {10,20,30}

    0 like 0 dislike
    by (120 points)

    01. Write a Python Program to sort (ascending and descending) a dictionary by value.

     Ans..import operator

     a={0:5,1:8,2:6,3:9,4:1}

     print('dictionary,a) 

    b=sorted(a.items(0.key%-operator.itemgetter(1)) print('ascending order',b) 

    c=sorted(a.items().key%3Doperator.itemgetter(1),reverse=true)

    print('descending order",c) 

    Q2.Write a Python Program to add a key to a dictionary. 

    Sample Dictionary : {0:10,1:20,2:30}

     Expected Result : {0:10,1:20,2:30,3:40}

    Ans:- x={0:10,1:20,2:30}

     x[3]=40

    print(x)

    O/P: x={0:10,1:20,2:30,3:40}

    Q. 4 Write a Python program to convert list to list of dictionaries. 

    Sample lists: ["Black", "Red", "Maroon", "Yellow"]. ("#000000", "#FF0000", "#800000", "#FFFF00"] Expected Output: [{'color_name: 'Black', 'color_code #000000'), (color_name 'Red', 'color code: '#FF0000'), ('color_name': 'Maroon', 'color cade: #800000'), (color_name": "Yellow, 'color code': '#FFFF00'}] 

    Ans: color_name= ["Black", "Red", "Maroon", "Yellow"]

    Q5.(1).Using above create a dictionary of Employees and thier salary

    Ans: a={"John":14,"Smith":13,"Alice":32,"Dail":21}

            print("employees names: Salary",a)

    Sets Questions-

    Q1.What is the difference between a set and a frozenset? Create any set and try to use frozenset(setname).

     Ans- A set la mutable and frozenset is immutable. we can not add or remove in frozenset is created. 

    set=("mumbai","delhi","chennai")

     a=frozenset(set) 

    print(set) 

    b=a.add(banglore) 

    print(b) 

    O/P frozenset' object has no attribute 'add' 

    Q.2 Find the elements in a given set that are not in another set 

    set 1 = (10,20,30,40,50) 

    set2 = (40,50,60,70,80) 

    Ans- set1={10,20,30,40,50) 

    set2 = (40,50,60,70,80)

    a= set1 difference(set2)

     print(a) 

    O/P :(10,20,30)

    0 like 0 dislike
    by (138 points)

    task 3 answer in my linkedin: https://www.linkedin.com/pulse/assignmenttask-3-aswin-kumar

    0 like 0 dislike
    by (110 points)

    Task -3 [GO_STP_9884]

    Q.1 

    dic = {'A':2'Z':3'H':1'x':6}

    print("original dictionary: ",dic)

    asc_dic = sorted(dic.items(), key=lambda x:x[1])

    print("Ascending order: ",asc_dic);

    dec_dic = sorted(dic.items(), key=lambda x:x[1], reverse=True)

    print("descending order: ",dec_dic);

    Q.2  

    dic = {010120

    print("Original dictionary: ",dic)

    dic[2]=30

    print("After insert new item in Dictionary: ",dic)

    Q.3

    cityName = input("enter the city name")

    tempName = int(input("enter temperature"))

    dic = {'city':cityName, 'temp':tempName}

    print(dic)

    Q.4

    originalList = ["Black""Red""Maroon""Yellow"], ["#000000""#FF0000""#800000""#FFFF00"]

    #print("Original List :",originalList)

    color_name = originalList[0]

    color_code = originalList[1]

    # create Dictionary

    print([{'color_name': f, 'color_code': c} for f, c in zip(color_name, color_code) ])

    Q.5

    #create Dictionary

    original = {'Employee':('John''Smith''Alice''Daneil'),'Salary': (14133221)}

    print(original)

    new = dict()

    for i in range(len(original['Employee'])):

        new[original['Employee'][i]] = original['Salary'][i]

    print(new)

    for i in new.keys():

      print(i,'==>',new[i])            

    n = input().strip().lower()

    def check(n):

      if n=='adds'#B Add

        e=input('Employee: ')

        if e in new:

          print("Employee exists")

        else:

          sal=int(input())

          new[e]=sal

          print(new)

      elif n=='remove':  # C:Remove

        e=input('Employee name: ')

        if e in new:

          new.pop(e)

          print(new)

        else:

          print("Employee doesn't exits!")  

      elif n=='print':

        e=input('Employee name: ')

        if e in new:

          print(new.get(e))

        else:

          print("Employee doesn't exits!")  

    check(n)

    Q.6

    sets = {1,2,3,4,5,4# Duplicate value but not consider

    print("Original Set: ",sets)

    sets.add(6# Add new element in set

    print("After insert: ",sets)

    # set to forzenset

    setName = frozenset(sets)

    print(setName)

    # forzenset to set

    setName = set(setName) # use forzenset

    print(sets)

    Q.7

    set1 = {10,20,30,40,50}

     set2 = {40,50,60,70,80}

    print("Difference between set1 and set2 is ",set1 - set2)

    3.3k questions

    7.1k answers

    394 comments

    4.6k users

    Related questions

     Goeduhub:

    About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
    ...