Python

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

1.

program to demonstrate use of dictionary in python with their function


# Create a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 4}

# Print the dictionary


print(my_dict)

# Get the value for a key


print(my_dict['apple'])

# Add a new key-value pair


my_dict['pear'] = 5

# Print the updated dictionary


print(my_dict)

# Remove a key-value pair


del my_dict['banana']

# Print the updated dictionary


print(my_dict)

# Get the number of items in the dictionary


print(len(my_dict))

# Check if a key exists in the dictionary


print('banana' in my_dict)

# Get a list of all the keys in the dictionary


print(my_dict.keys())

# Get a list of all the values in the dictionary


print(my_dict.values())

# Get a list of all the key-value pairs in the dictionary


print(my_dict.items())

2. wap to calculate mean median mode in list python

def mean(nums):

return sum(nums) / len(nums)

def median(nums):

nums.sort()

length = len(nums)

if length % 2 == 0:
return (nums[length // 2 - 1] + nums[length // 2]) / 2

else:

return nums[length // 2]

def mode(nums):

nums.sort()

return max(set(nums), key=nums.count)

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("Mean:", mean(nums))

print("Median:", median(nums))

print("Mode:", mode(nums))

3.

You might also like