Dictionaries
Dictionaries
Dictionaries
What is a dictionary?
>>> mydic.values()
dict_values([3,10])
19-12-2021
• get()
It takes one to two arguments. Where the
first is the key to search for,(if key found it
returns the value) the second is the value to
return if the key isn’t found.
The default value for this second argument
is None.
Syntax:
dictionaryname.get(key,returnvalue)
Example:
dict4={1:11,2:22,3:33,4:44}
>>> dict4.get(3,0) # 33
>>> dict4.get(5,0) # 0
>>> dict4.get(5) # None
NOTE : Since the key 5 wasn’t in the
dictionary, it returned 0, like we
specified and None when not given
>>>dict4.get(7,'not')
'not'
19-12-2021
• clear()
It empties the dictionary.
Syntax: dictionaryname.clear()
Example:
>>> dict4.clear()
It can be reassigned for further use.
>>> dict4={3:3,1:1,4:4}
( It is possible)
• items()
It returns a list of key-value pairs.
Syntax:
dictionaryname.items()
Example:
>>> dict4.items()
dict_items([(3, 3), (1, 1), (4, 4)])
19-12-2021
• update()
It takes another dictionary as argument.
Then it updates the dictionary to hold values
from the other dictionary that it doesn’t have
already.
>>> dict1={1:1,2:2}
>>> dict2={2:20,3:3}
>>> dict1.update(dict2)
>>> dict1
{1: 1, 2: 20, 3: 3}
• Deleting elements from a dictionary
A) del command Syntax: del DicName[key]
Example:
>>> mydic = {'bill':3, 'rich':10}
>>>del mydic[‘bill’]
>>>print (mydic) #{‘rich’:10}
B) By using pop() function : Syntax: dictionary.pop(key)
Example: >>>mydic.pop(‘bill’)
3
( pop() will also return the value which has been deleted)
>>>print(mydic) #{‘rich’:10}
NOTE: del dic Name will delete the entire dictionary.
Like : del mydic # it will delete the dictionary