Advertisement
brandblox

python lab (23/04/2024)

Apr 23rd, 2024
635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. # Creating a dictionary with key-value pairs using dict() function taking user input
  2.  
  3. my_dict = {}
  4. num_pairs = int(input("Enter the number of key-value pairs: "))
  5.  
  6. for i in range(num_pairs):
  7.     key = input("Enter key {}: ".format(i+1))
  8.     value = input("Enter value {}: ".format(i+1))
  9.     my_dict[key] = value
  10.  
  11. print("Dictionary created:", my_dict)
  12.  
  13. #output
  14. Enter the number of key-value pairs: 2
  15. Enter key 1: hello
  16. Enter value 1: 2
  17. Enter key 2: word
  18. Enter value 2: 2
  19. Dictionary created: {'hello': '2', 'word': '2'}
  20.  
  21.  
  22. #WAP in python to insert three elements and Pop 1 element from a Dictionary.
  23.  
  24. my_dict = {}
  25.  
  26. my_dict['apple'] = 10
  27. my_dict['banana'] = 20
  28. my_dict['orange'] = 30
  29.  
  30. print("Original dictionary:", my_dict)
  31.  
  32. popped_item = my_dict.popitem()
  33.  
  34. print("Popped item:", popped_item)
  35. print("Dictionary after popping one element:", my_dict)
  36.  
  37. #output:
  38. Original dictionary: {'apple': 10, 'banana': 20, 'orange': 30}
  39. Popped item: ('orange', 30)
  40. Dictionary after popping one element: {'apple': 10, 'banana': 20}
  41.  
  42.  
  43. #WAP in python to find sum of all items in a Dictionary
  44.  
  45. my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
  46. total_sum = sum(my_dict.values())
  47. print("Sum of all items in the dictionary:", total_sum)
  48.  
  49. #output:
  50. Sum of all items in the dictionary: 100
  51.  
  52.  
  53. # WAP in python update the value of a dictionary in Python if the particular key exists. If the key is not
  54. #present in the dictionary, we will simply print that the key does not exist
  55.  
  56. my_dict = {'a': 10, 'b': 20, 'c': 30}
  57.  
  58. key_to_update = input("Enter the key to update: ")
  59. new_value = input("Enter the new value: ")
  60.  
  61. if key_to_update in my_dict:
  62.     my_dict[key_to_update] = new_value
  63. else:
  64.     print("The key does not exist")
  65.  
  66. print("Updated dictionary:", my_dict)
  67.  
  68. #output:
  69. Enter the key to update: a
  70. Enter the new value: 6
  71. Updated dictionary: {'a': '6', 'b': 20, 'c': 30}
  72.  
  73.  
  74. #Write a program to get the maximum and minimum value of dictionary
  75.  
  76. my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 5}
  77.  
  78. max_value = max(my_dict.values())
  79. min_value = min(my_dict.values())
  80.  
  81. print("Maximum value in the dictionary:", max_value)
  82. print("Minimum value in the dictionary:", min_value)
  83.  
  84.  
  85. #output
  86. Maximum value in the dictionary: 30
  87. Minimum value in the dictionary: 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement