Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Dictionary

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

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


Dict.keys()
dict_keys([1, 2, 3])
Dict.values()
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 syntax.It 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}
Employee.pop('age')
24

(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}

You might also like