Day-4:
Dictionaries
and
Functions
26/06/2018
Department Of
Computer Science
Engineering
SKFGI, Mankundu
, Dictionaries
1. What is dictionary in Python?
Python dictionary is an unordered collection of items. While other compound
data types have only value as an element, a dictionary has a key: value
pair.
Dictionaries are optimized to retrieve values when the key is known.
2. How to 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 1
# empty dictionary
my_dict = {}
Example 2
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
Example 3
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
,Example 4
thisdict ={ "apple": "green", "banana": "yellow", "cherry": "red"}
print(thisdict)
Output :
{'apple': 'green', 'banana': 'yellow', 'cherry': 'red'}
It is also possible to use the dict() constructor to make a dictionary:
Example 5
thisdict = dict(apple="green", banana="yellow", cherry="red")
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Output
{'apple': 'green', 'banana': 'yellow', 'cherry': 'red'}
3. How to access elements from a dictionary?
To access dictionary elements, you can use the familiar square brackets
along with the key to obtain its value.
Example 1
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Output:-
dict['Name']: Zara
dict['Age']: 7
Example 2
If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error as follows –
, dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Alice']: ", dict['Alice'])
Output:
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Key can also be used with the get() method.
The difference while using get() is that it returns None instead of KeyError,
if the key is not found.
Example 3
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name'])
Output:
Jack
print(my_dict.get('age'))
Output :
26
# Trying to access keys which doesn't exist throws error
# my_dict.get('address')
# my_dict['address']
Dictionaries
and
Functions
26/06/2018
Department Of
Computer Science
Engineering
SKFGI, Mankundu
, Dictionaries
1. What is dictionary in Python?
Python dictionary is an unordered collection of items. While other compound
data types have only value as an element, a dictionary has a key: value
pair.
Dictionaries are optimized to retrieve values when the key is known.
2. How to 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 1
# empty dictionary
my_dict = {}
Example 2
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
Example 3
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
,Example 4
thisdict ={ "apple": "green", "banana": "yellow", "cherry": "red"}
print(thisdict)
Output :
{'apple': 'green', 'banana': 'yellow', 'cherry': 'red'}
It is also possible to use the dict() constructor to make a dictionary:
Example 5
thisdict = dict(apple="green", banana="yellow", cherry="red")
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Output
{'apple': 'green', 'banana': 'yellow', 'cherry': 'red'}
3. How to access elements from a dictionary?
To access dictionary elements, you can use the familiar square brackets
along with the key to obtain its value.
Example 1
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Output:-
dict['Name']: Zara
dict['Age']: 7
Example 2
If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error as follows –
, dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Alice']: ", dict['Alice'])
Output:
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Key can also be used with the get() method.
The difference while using get() is that it returns None instead of KeyError,
if the key is not found.
Example 3
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name'])
Output:
Jack
print(my_dict.get('age'))
Output :
26
# Trying to access keys which doesn't exist throws error
# my_dict.get('address')
# my_dict['address']