Python - Dict
Python - Dict
Below are the two lists. Write a Python program to convert them into a dictionary in a way that item
from list1 is the key and item from list2 is the value. The output should be:
print(res_dict)
# empty dictionary
res_dict = dict()
for i in range(len(keys)):
res_dict.update({keys[i]: values[i]})
print(res_dict)
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict3 = dict1.copy()
dict3.update(dict2)
print(dict3)
Given:
Solution
print(res)
# Individual data
print(res["Kelly"])
Write a Python program to create a new dictionary by extracting the mentioned keys from the below
dictionary.
Given dictionary:
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
Solution1:
Expected output:
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
print(newDict)
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
# keys to extract
# new dict
res = dict()
for k in keys:
res.update({k: sample_dict[k]})
print(res)
Exercise 5: Delete a list of keys from a dictionary
Given:
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
# Keys to remove
Expected output:
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
# Keys to remove
for k in keys:
sample_dict.pop(k)
print(sample_dict)
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
# Keys to remove
print(sample_dict)
We know how to check if the key exists in a dictionary. Sometimes it is required to check if the given
value is present.
Write a Python program to check if value 200 exists in the following dictionary.
Given:
Expected output:
if 200 in sample_dict.values():
Given:
sample_dict = {
"name": "Kelly",
"age":25,
"salary": 8000,
}
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
sample_dict['location'] = sample_dict.pop('city')
print(sample_dict)
Write a Python program to change Brad’s salary to 8500 in the following dictionary.
Given:
sample_dict = {
Expected output:
Solution
sample_dict = {
}
sample_dict['emp3']['salary'] = 8500
print(sample_dict)