Dictionary
Dictionary
Dictionary
Elements are accessed through the keys defined in the key:value pairs.
<dictionary-name>[<key>]
Dict[1]
'Apple'
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
(iii)If you try to delete a key which does not exist, Python return error.
Employee.pop('new')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
Employee.pop('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}
Employee.pop('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])
Employee.get('name')
'John'
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("name")
print(x)
None
4. Items()
This method returns all of the items in the dictionary as a sequence of (key,
value)tuples
Employee.items()
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
Employee.keys()
dict_keys(['name', 'salary', 'age'])
6. Values()
This method returns all the values from the dictionary as a sequence (a list)
Employee.values()
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}
Employee.update(Employee1)
Employee
{'name': 'Diya', 'salary': 540000, 'age': 30}