DICITIONARY
A dictionary is a unordered collection of key and value pairs.(ordered
collection before 3.6 version)
It is built-in mapping data type.
Unlike the string , list and tuple , a dictionary is not a sequence
because it is unordered set of elements.
Dictionaries are indexed by keys and its keys must be of any non-
mutable type.
Each of the keys within a dictionary must be unique.
Dictionaries are written with curly brackets, and have keys and values
Dictionary items are presented in key:value pairs, and can be referred
to by using the key name.
Dict = {1: 'Apple', 2: 'Banana', 3: 'Orange'}
print(Dict)
{1: 'Apple', 2: 'Banana', 3: 'Orange'}
Accessing Elements of a dictionary
Elements are accessed through the keys defined in the key:value pairs.
<dictionary-name>[<key>]
Dict[1]
'Apple'
Accessing only keys or values
[Link]()
dict_keys([1, 2, 3])
[Link]()
dict_values(['Apple', 'Banana', 'Orange'])
DICTIONARY OPERATIONS
Traversing a Dictionary
Traversal of a collection means accessing and processing each element of it.
For <item> in <Dictionary>:
Process each item here
d1={5:"number",\
"a":"string",\
(1,2):"tuple"}
for key in d1:
print(key,":",d1[key])
5 : number
a : string
(1, 2) : tuple
Adding new Elements to Dictionary
We can add new elements (key:value pair) to a dictionary using assignment as
the following [Link] must be unique.
<dictionary>[<key>]=<value>
Employee={'name':'John','salary':10000,'age':24}
Employee["dept"]='Sales'
print(Employee)
{'name': 'John', 'salary': 10000, 'age': 24, 'dept': 'Sales'}
Updating Existing Elements in Dictionary
Dictionary[<key>]=<value>
Employee={'name':'John','salary':10000,'age':24}
Employee["salary"]=20000
print(Employee)
{'name': 'John', 'salary': 20000, 'age': 24}
Deleting Elements from a Dictionary
(i)Del command delete a dictionary element or a dictionary entry
Del<dictionary>[<key>]
Employee={'name':'John','salary':10000,'age':24}
del Employee['salary']
print(Employee)
{'name': 'John', 'age': 24}
(ii)Another method to delete elements from a dictionary is by using pop()
The pop() method will delete the key:value pair for mentioned key but also
return the corresponding value.
Employee={'name':'John','salary':10000,'age':24}
Employee
{'name': 'John', 'salary': 10000, 'age': 24}
[Link]('age')
24
(iii)If you try to delete a key which does not exist, Python return error.
[Link]('new')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
[Link]('new')
KeyError: 'new'
(iv)pop() method allows you to specify what to display when the given key does
not exist , as per following syntax:
<dictionary>.pop(<key>,<in case of error show me>)
Employee
{'name': 'John', 'salary': 10000}
[Link]('new',"Not found")
'Not found'
Dictionary Function
1. Len()
This method return length of the dictionary, i.e the count of elements in the
dictionary.
Employee={'name':'John','salary':10000,'age':24}
len(Employee)
3
2. Clear()
3. Get()
This method will get the item with the given key, if the key is not present , python will
give error
<dictionary>.get(key,[default])
[Link]('name')
'John'
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("name")
print(x)
None
4. Items()
This method returns all of the items in the dictionary as a sequence of (key,
value)tuples
[Link]()
dict_items([('name', 'John'), ('salary', 10000), ('age', 24)])
5. Keys()
This method returns all of the keys in the dictionary as a sequence of key
[Link]()
dict_keys(['name', 'salary', 'age'])
6. Values()
This method returns all the values from the dictionary as a sequence (a list)
[Link]()
dict_values(['John', 10000, 24])
7. Update()
This method merges key:value pairs from the new dictionary into original dictionary.
Employee1={'name':'Diya','salary':540000,'age':30}
Employee1
{'name': 'Diya', 'salary': 540000, 'age': 30}
[Link](Employee1)
Employee
{'name': 'Diya', 'salary': 540000, 'age': 30}