Dictionary
Dictionary
Python dictionary is an unordered collection of items. data types have only value as an element, a
dictionary has a key: value pair.
create a dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An
item has a key and the corresponding value expressed as a pair, key: value. While values can be of
any data type and can repeat, keys must be of immutable type (string, number or tuple with
immutable elements) and must be unique.
Example
# empty dictionary
my_dict = {}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
squares = {}
print "Enter your key and integer vlaues"
for x in range(3):
x=input("Enter your key")
y=input("Enter your value")
squares[x] = y
print squares
or
You can give the input in terminal in one single line by placing all the items in curly braces
seperated by comma
example
Example
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print my_dict['name']#John
print my_dict.get('age')#None
print my_dict.get('age',' key is not found')#key is not found(if the key is exist it will print value)
print my_dict.get(''name'',' key is not found')#'John'
print my_dict['age']#Keyerror
change or add elements in a dictionary
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator. If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.
Example
my_dict = {'name': 'John', 1: [2, 4, 3]}
# update value
my_dict['name'] = 'jack'
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
my_dict[1][2]=10
print (my_dict)
We can also use the del keyword to remove individual items or the entire dictionary itself.
Example
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# remove a particular item
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item
# Output: (1, 1)
print(squares.popitem())
# Output: {2: 4, 3: 9, 5: 25}
print(squares)
# delete a particular item
del squares[5]
# Output: {2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error it is not defined
# print(squares)
Iterating Through a Dictionary
Using a for loop we can iterate though each key in a dictionary.
Example
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is
for keys only, not for values.
Example
# Output: True
print(2 not in squares)
We can test if a key have that value or not in a sequence by using membership operaor.
Example
d={'a':[1,2,3],'b':[4,5,6]}
print 2 in d['a']#Output: True
print 4 in d['a']#Output:False
all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
Syntax:all(iterable)
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
Syntax:any(iterable)
Example
import operator
mydict={12:3,19:1,0:0,21:8}
print sorted(mydict)#print the keys in ascending order
print sorted(mydict,reverse=True)#Print the keys in descending order
print sorted(mydict.values())#Values in ascending order
print sorted(mydict.values(),reverse=True)#Values in descending order
print sorted(mydict.items())#sort the keys in ascending order and print keys and values
print sorted(mydict.items(),reverse=True)#sort the keys in descending order and print keys and
values
print sorted(mydict.items(), key=operator.itemgetter(1))#sort the values in ascending order and print
keys and values
print sorted(mydict.items(), key=operator.itemgetter(0))#sort the keys in ascending order and print
keys and values
print all(mydict)
print any(mydict)
print len(mydict)
Note:itemgetter(position) returns a callable, that takes a sequence, and returns the value at position
in sequence.
Dictionary Methods
values() return a new view of the dictionary's values
Syntax:dictionary.values()
copy() returns a shallow copy of the dictionary. It doesn't modify the original dictionary. The
difference between copy method and = operator is When copy() method is used, a new dictionary is
created which is filled with a copy of the references from the original dictionary.When = operator is
used, a new reference to the original dictionary is created.
Syntax:dict.copy()
Clear() removes all items in the dictionary but not the dictionary itself.It will return an empty
dictionary
Syntax:dict.clear()
update([other]) The update() method adds element(s) to the dictionary if the key is not in the
dictionary. If the key is in the dictionary, it updates the key with the new value.The update() method
takes either a dictionary or an iterable object of key/value pairs (generally tuples).
items() The items() method returns a view object that displays a list of a given dictionary's (key,
value) tuple pair.
Syntax:dictionary.items()
pop Remove the item with key and return its value or if key is not found, raises KeyError.
Syntax:dictionary.pop(key[, default])
popitem() Remove and return an arbitary item (the element was not chosen by you it is
unpredictable key, value pair). Raises KeyError if the dictionary is empty.
Syntax:dict.popitem()
Example
Exercise programs
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
4. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both
included) and the values are square of keys?
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196,
15: 225}
5. Python Program to Create a Dictionary with Key as First Character of the string and Value as
Words Starting with that Character in that string
6. Write a Python program to count number of items in a dictionary value that is a list.
7. Write a Python program to count of the letters from the string and create a dictionary from a
string.
8. Create a dictionary to hold information about pets. Each key is an animal's name, and each value
is the animal baby name.
For example, 'cat': 'kitten'
Put at least 3 key-value pairs in your dictionary.
Use a for loop to print out a series of statements such as "cat baby name is kitten"