Data Science Practical

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Name :- Ritik Kumar

Reg. No. - 12214480

Roll no.- A16


1. Print the value of key ‘history’ from the below
dictionary.

Code:- # Initialize a dictionary


my_dict = {'history': 'World War II', 'science': 'Physics', 'math':
'Algebra'}

# Print the value associated with the 'history' key


print(my_dict['history'])
OUTPUT:-

2. Initialize dictionary for key values


Code:-
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Using the dict() constructor


my_dict = dict(key1='value1', key2='value2', key3='value3')
3. Create a dictionary by extracting the keys from a given
dictionary
Code:-
# Existing dictionary
original_dict = {'name': 'Ritik', 'age': 20, 'city': 'Ludhiana'}

# Extract keys and create a new dictionary with just the keys
keys_dict = {key: None for key in original_dict.keys()}

# Print the new dictionary containing only the keys


print(keys_dict)

OUTPUT:-

4. Delete a list of keys from a dictionary ?

Code :-
# Original dictionary
my_dict = {'name': 'Ray', 'age': 23, 'city': 'Jalandhar', 'gender': 'Male'}

# List of keys to delete


keys_to_delete = ['age', 'gender']

# Delete the keys from the dictionary


for key in keys_to_delete:
if key in my_dict:
del my_dict[key]

# Print the modified dictionary


print(my_dict)

OUTPUT :-

5. Check if a value exists in a dictionary33 ?

Code:-
# Sample dictionary
my_dict = {'name': 'Rocko', 'age': '33', 'city': 'Phagwara'}

# Value to check
value_to_check = '33'

# Check if the value exists in the dictionary's values


if value_to_check in my_dict.values():
print(f'The value "{value_to_check}" exists in the dictionary.')
else:
print(f'The value "{value_to_check}" does not exist in the
dictionary.')

OUTPUT:-

6. Rename key of a dictionary ?

CODE:-

# Original dictionary
my_dict = {'old_key': 'value'}

# Define the new key


new_key = 'new_key'

# Create a new key-value pair and delete the old key


my_dict[new_key] = my_dict.pop('old_key')

# Print the modified dictionary


print(my_dict)

OUTPUT:-

7. Change value of a key in a nested dictionary ?

Code:-

# Original nested dictionary


my_dict = {
'person': {
'name': 'radhe',
'age': '20',
},
'location': {
'city': 'Vrindawan',
'state': 'U.P',
}
}

# Change the value of the 'age' key in the nested dictionary


new_age = 35
my_dict['person']['age'] = new_age

# Print the modified dictionary


print(my_dict)

OUTPUT:-

You might also like