You are on page 1of 9

Dictionary

Dictionary
• Dictionary is an unordered set of key and value pair.
• It is an container that contains data, enclosed within
curly braces{}.
• The pair i.e., key and value is known as item.
• The key passed in the item must be unique.
• The key and the value is separated by a colon(:). This
pair is known as item. Items are separated from each
other by a comma(,). Different items are enclosed
within a curly brace and this forms Dictionary.
• keys must be of an immutable data type such as
strings, numbers, or tuples.
Declaration and Creation
• Empty Dictionary
Key Value
d={}
• Dictionary Initialization
d={"name":"john","age":20,"country":"India"}
print(d)
Output:- {'name': 'john', 'country': 'India', 'age':
20}
Dict-adding and deleting element
Example:- Adding new key-value pair

d={"name":"john","age":20,"country":"India"}
d["city“]="kanpur“
Example :- Deleting key-value pair
del d["name"]
Accessing by iterating elements
• Example:-
my_dict={"john":45,"amit":12,"sumit":100}
for k, v in my_dict.items():
print(k,v)
Output:- amit 12
sumit 100
john 45
Updating Dictionary
Example:-
Change the value of “john”
my_dict={"john":45,"amit":12,"sumit":100}
my_dict["john"]=50
Sorting on value basis
Example
d={"amit":30,"raj":100,"anil":20}
for v in sorted(d.values()):
print(v)
Output:- 20
30
100
Sorting on key basis
Example:-
d={"zishan":30,"raj":100,"anil":20}
for k in sorted(d.keys()):
print(k)
Output:-
anil
raj
zishan
Sorting in reverse order
d={"zishan":30,"anil":100,"raj":20}
for k in sorted(d.keys(),reverse=True):
print(k)
Output:-
zishan
raj
anil

You might also like