Written by students who passed Immediately available after payment Read online or as PDF Wrong document? Swap it for free 4.6 TrustPilot
logo-home
Study guide

Python Beginner Course Note-4

Rating
-
Sold
-
Pages
37
Uploaded on
15-09-2020
Written in
2019/2020

This is the continuation of my crash course on Python. This material contains compact, briefed concepts about dictionaries and functions in Python.

Institution
Course

Content preview

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']

Connected book

Written for

Institution
Course

Document information

Uploaded on
September 15, 2020
Number of pages
37
Written in
2019/2020
Type
Study guide

Subjects

$5.99
Get access to the full document:

Wrong document? Swap it for free Within 14 days of purchase and before downloading, you can choose a different document. You can simply spend the amount again.
Written by students who passed
Immediately available after payment
Read online or as PDF

Get to know the seller
Seller avatar
snehat1410

Get to know the seller

Seller avatar
snehat1410 MAKAUT
Follow You need to be logged in order to follow users or courses
Sold
1
Member since
5 year
Number of followers
1
Documents
14
Last sold
5 year ago

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Recently viewed by you

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their tests and reviewed by others who've used these notes.

Didn't get what you expected? Choose another document

No worries! You can instantly pick a different document that better fits what you're looking for.

Pay as you like, start learning right away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and aced it. It really can be that simple.”

Alisha Student

Working on your references?

Create accurate citations in APA, MLA and Harvard with our free citation generator.

Working on your references?

Frequently asked questions