Python Dictionary
- Categories Python Dictionary, Python
In this post we will cover Dictionary in Python. You can watch our videos on Dictionary in Python – Click Here
Q. 1 Write a short note on Dictionary in python?
Ans.
- Dictionaries are Mutable
- Unordered collections where items are accessed by a key, not by the position in the list. So is not a sequence
- In dictionaries keys are Unique
- Dictionaries are Nestable
- It can grow and shrink in place like lists
- Internally stored as mappings (hash function)
- Concatenation, slicing, and other operations that depend on the order of elements do not work on dictionaries
Q.2 How to create a python Dictionary?
Ans.
- It is enclosed in curly braces {} and each item is separated from other item by a comma(,).
- Within each item, key and value are separated by a colon (:).
- Passing value in dictionary at declaration is dictionary initialization.get() method is used to access value of a key
- e.g. dict = {‘Subject’: ‘Python’, ‘Class’: ‘10′}
- some way to create dictionary:
- Create Empty Dictionary
- E = {}
- E = dict()
- Creating from key:value pairs
- E = { “name”:”Minal”, “salary”:4000,”Age” : 40}
- E = dict({“name”:”Minal”, “salary”:4000,”Age” : 40})
- E=dict(zip(“name”,”salary”,”age”),(“Minal”,4000,40))
- E=dict((“name”,”Minal”), (“salary”,4000),(”Age” , 40)) #does not work
- E = dict(“name”:”Minal”, “salary”:4000,”Age” : 40) # does not work
- Creating from lists
- keys = [‘david’, ‘chris’, ‘stewart’]
- vals = [‘504’, ‘637’, ‘921’]
- D = dict(zip(keys, vals))
- fromkeys(listOfStr , 1) # 1 is default value for all keys
- Adding elements to dictionary
- E[‘dept’] = “HR”
Q. 3 ____ method is used to remove all elements from the dictionary.
Ans. clear()
Q. 4 _____ method is used to remove a particular item in a dictionary
Ans. pop()
Q. 5 How to update dictionary?
Ans. To updating dictionary:
- We can change the individual element of dictionary.
- e. g.
dict = {‘Subject’: ‘Python’, ‘Class’: 11}
dict[‘Subject’]=’computer science’
print(dict) - {‘Class’: 11, ‘Subject’: ‘computer science’}
Q.6 How we can delete dictionary elements?
Ans.
- del, pop() and clear() statement are used to remove elements from the dictionary.
- del e.g.
dict = {‘Subject’: ‘Informatics Practices’, ‘Class’: 11}
print(‘before del’, dict)
del dict[‘Class’] # delete single element
print(‘after item delete’, dict)
del dict #delete whole dictionary
print(‘after dictionary delete’, dict) - Output
(‘before del’, {‘Class’: 11, ‘Subject’: ‘Informatics Practices’})
(‘after item delete’, {‘Subject’: ‘Informatics Practices’})
(‘after dictionary delete’, <type ‘dict’>)
Q.7 How do Searching is done in Dictionary?
Ans.
- First it see if a key is in dictionary
d.has_key(‘keyname’) or ‘keyname’ in d - Search in values
in d.values() - get() method useful to return value but not fail (return None) if key doesn’t exist (or can provide a default value)
d.get(‘keyval’, default) - update() merges one dictionary with another (overwriting values with same key)
d.update(d2) [the dictionary version of concatenation]
Q. 8 Predict the output for following code.
D = {“Ronit”:1,”Nihir”:2,”Yuvna”:30,”fiza”:20}
temp = 0
for a in D.values() :
temp += a
print(temp)
Ans. Output: 53
Q. 9 Predict the output for following code.
D = {“Ronit”:1,”Nihir”:2,”Yuvna”:30,”fiza”:20}
K = “Ronit”
V = -1
if K in D:
D[K] = V
print(D)
Ans. Output: {‘Ronit’: -1, ‘Nihir’: 2, ‘Yuvna’: 30, ‘fiza’: 20}
Q. 10 Write a Python program to count the number of characters (character frequency) in a string.
Ans.
def c(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print(c('simplycoding.in'))
Q. 11 Write a python program to Check for Key in Dictionary Value list.
Ans.
test_dict = {'Simply' : [{'CS' : 5}, {'Python' : 6}], 'for' : 2, 'CS' : 3}
print("The original dictionary is : " + str(test_dict))
key = "Python"
res = any(key in ele for ele in test_dict['Simply'])
print("Is key present in nested dictionary list ? : " + str(res))
Q. 12 Write a python program to Concatenate Dictionary string values.
Ans.
test_dict1 = {'SC' : 'a', 'is' : 'b', 'best' : 'c'}
test_dict2 = {'SC' : '1', 'is' : '2', 'best' : '3'}
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
res = {key: test_dict1[key] + test_dict2.get(key, '') for key in test_dict1.keys()}
print("The string concatenation of dictionary is : " + str(res))
Q. 13 Write a python program to print Keys with Maximum value from dictionary.
Ans.
test_dict = {'Simply' : 2, 'Coding' : 1, 'Python' : 3, 'java': 2}
print("The original dictionary is : " + str(test_dict))
temp = max(test_dict.values())
res = [key for key in test_dict if test_dict[key] == temp]
print("Keys with maximum values are : " + str(res))
Q. 14 Write a python program to find dictionary Keys Product.
Ans.
test_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}
test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10}
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
res = {key: test_dict2[key] * test_dict1.get(key, 0)for key in test_dict2.keys()}
print("The product dictionary is : " + str(res))