Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Creating a dictionary with key-value pairs using dict() function taking user input
- my_dict = {}
- num_pairs = int(input("Enter the number of key-value pairs: "))
- for i in range(num_pairs):
- key = input("Enter key {}: ".format(i+1))
- value = input("Enter value {}: ".format(i+1))
- my_dict[key] = value
- print("Dictionary created:", my_dict)
- #output
- Enter the number of key-value pairs: 2
- Enter key 1: hello
- Enter value 1: 2
- Enter key 2: word
- Enter value 2: 2
- Dictionary created: {'hello': '2', 'word': '2'}
- #WAP in python to insert three elements and Pop 1 element from a Dictionary.
- my_dict = {}
- my_dict['apple'] = 10
- my_dict['banana'] = 20
- my_dict['orange'] = 30
- print("Original dictionary:", my_dict)
- popped_item = my_dict.popitem()
- print("Popped item:", popped_item)
- print("Dictionary after popping one element:", my_dict)
- #output:
- Original dictionary: {'apple': 10, 'banana': 20, 'orange': 30}
- Popped item: ('orange', 30)
- Dictionary after popping one element: {'apple': 10, 'banana': 20}
- #WAP in python to find sum of all items in a Dictionary
- my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
- total_sum = sum(my_dict.values())
- print("Sum of all items in the dictionary:", total_sum)
- #output:
- Sum of all items in the dictionary: 100
- # WAP in python update the value of a dictionary in Python if the particular key exists. If the key is not
- #present in the dictionary, we will simply print that the key does not exist
- my_dict = {'a': 10, 'b': 20, 'c': 30}
- key_to_update = input("Enter the key to update: ")
- new_value = input("Enter the new value: ")
- if key_to_update in my_dict:
- my_dict[key_to_update] = new_value
- else:
- print("The key does not exist")
- print("Updated dictionary:", my_dict)
- #output:
- Enter the key to update: a
- Enter the new value: 6
- Updated dictionary: {'a': '6', 'b': 20, 'c': 30}
- #Write a program to get the maximum and minimum value of dictionary
- my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 5}
- max_value = max(my_dict.values())
- min_value = min(my_dict.values())
- print("Maximum value in the dictionary:", max_value)
- print("Minimum value in the dictionary:", min_value)
- #output
- Maximum value in the dictionary: 30
- Minimum value in the dictionary: 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement