SlideShare a Scribd company logo
PYTHON DICTIONARIES
A Story of Two Collections..
• List
- A linear collection of values that stay in order
• Dictionary
- A “bag” of values, each with its own label
INTRODUCTION
• Dictionary are mutable, unordered collection with elements
in the form of a key:value pairs that associate keys to values.
• Rather than index associated with lists, tuples and
strings,a dictionary has key associated with values.
• It is just like English Dictionary where meaning is associated with a word
(Key).
• Dictionaries are containers that associate keys to values.
• With list, tuples and strings we need to know the index of
individual element to access but with Dictionaries user need to search
value based on key.
>>>Month={“January":31,"February":28,"March":31,"April":30,
"May":31,"June":30,"July":31,"August":31,"September":30,"October":31,"
November":30, "December":31}
>>> teacher={'kkp':'9885139413','Prakash':'8604774180'}
Notice that:
1. Curly braces mark the beginning and end of the dictionary
2. Each entry (key:value) consists of a pair separated by a colon. The key
and corresponding value is given by writing colon(:) between them.
3. The key:value pairs are separated by comma.
Internally dictionaries are indexed (i.e.) arranged on the basis of keys.
CREATING AND ACCESSING LISTS
SOME MORE DICTIONARY DECLRATION
Emptydisctionary={ }
>>>daynumberofweek={"Monday":1, "Tuesday":2, "Wednesday":3,
"Thursday":4,"Friday":5,"Saturday":6,"Sunday":7}
>>> subjectandcode={"Physics":42,"Chemistry":43, "Mathematics":41,
"Biology":44,"ComputerScience":83,"Informatics
Practices":65,"English":101,"Hindi":2}
Note:
• Dictionaries are also called Associative Arrays or mappings or hashes.
• Keys of a dictionaries must be of immutable type such as Python string,
Number, a tuple (containing only immutable entry) but list which is mutable
cannot be used as keys of a dictionary.
>>>dict2={[2,3]:”abc”} #TypeError: Un-sharable Type ‘list’
ACCESSING OF A DICTIONARY
Its general syntax is dictionaryname<“key">
EXAMPLE:
>>> subjectandcode["Hindi"] 2
>>> subjectandcode["Computer Science"] 83
>>> subjectandcode["Informatics Practices"] 65
ACCESSING ENTIRE DICTIONARY
>>>dictionaryname
• Mentioning only the dictionary name without any key prints the entire dictionary.
• If the key in square bracket is used along with dictionaryname
produces the value that matches the key otherwise error
is
displayed.
Example:
>>> subjectandcode
{'Physics': 42, 'Chemistry': 43, 'Mathematics': 41,
'Biology': 44, 'Computer
Science': 83, 'Informatics Practices': 65, 'English': 101, 'Hindi': 2}
>>> subjectandcode["Hindi"] 2
• A dictionary operation that takes a key and finds the
corresponding value is called lookup.
• To access a particular value of the dictionary the key is provided in square
bracket is in double quote i.e. of string type.
• In python the elements (key:value pairs) are unordered. It means one can not
access elements as per specific order.
• References of keys and values are stored in dictionaries.
• Dictionaries are unordered set of elements, the printed order of
elements may or may not be in the order in which we have stored them in the
dictionary.
Access Dictionary Keys:Value one by one through Loop
>>> for subject in subjectandcode:
print(subject,":",subjectandcode[subject])
Physics : 42
Chemistry : 43
Mathematics : 41
Biology : 44
Computer Science : 83
Informatics Practices : 65
English : 101
Hindi : 2
Accessing Keys and Values
>>> subjectandcode.keys()
dict_keys(['Physics', 'Chemistry', 'Mathematics', 'Biology',
'Computer Science', 'Informatics Practices', 'English', 'Hindi'])
>>> subjectandcode.values() dict_values([42, 43,
41, 44, 83, 65,101, 2])
It can be converted in list as below
>>> list(subjectandcode.keys())
['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer
Science', 'Informatics Practices', 'English', 'Hindi']
>>> list(subjectandcode.values())
[42, 43, 41, 44, 83, 65, 101, 2]
Accessing Keys and Values
The keys of Dictionaries converted into list can be stored in a list
variable.
>>> Subject=list(subjectandcode.keys())
>>>Subject
['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer Science',
'Informatics Practices', 'English', 'Hindi']
>>> SubjectCode=list(subjectandcode.values())
>>>SubjectCode
[42, 43, 41, 44, 83, 65, 101, 2]
CHARACTERISTICS OF DICTIONARY
• Dictionary is mutable like list. Except this there is no
similarity with list. It has following attributes:
1. Unordered set: Dictionary is an unordered set of keys:value pairs. Its value can contain
references to any type of object.
2. Not a sequence: Unlike string,, lists and tuples a dictionary is not a sequence because
it is unordered
The sequence are indexed by range or ordinal numbers. Hence they are ordered
but dictionaries are unordered collection
.
3. Indexed by Keys and not Numbers: Dictionaries are indexed by keys. According to
Python, a key can be ”any non-mutable type”. Since Strings and Numbers are non
mutable it can be used as keys. Tuple if containing immutable objects (integers and
strings), can be used as keys. A value in a dictionary can be of any type and type can be
mixed within one dictionary.
CHARACTERISTICS OF DICTIONARY
4. Keys must be unique: Each of the keys within a dictionary must be unique. Since
keys are used to identify values in a dictionary, there can not be duplicate keys in
a dictionary. However two unique keys have same value.
5. Mutable: Like list, dictionaries are also mutable. We can change the value of
a certain key “in place” using the assignment statement as per following
syntax
<dictionary>[<key>]=<value>
>>> subjectandcode["Hindi"]=102
>>> subjectandcode
{'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44,
'Computer Science': 83, 'Informatics
Practices': 65, 'English': 101, 'Hindi': 102}
CHARACTERISTICS OF DICTIONARY
6. We can add new key:value pair to existing
dictionary:Using following syntax a new Key:value pair can be added to dictionary.
dictionary[“new”]=“a new pair is added”
>>> subjectandcode["Sanskrit"]=122
>>> subjectandcode
{'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44,
'Computer
Science': 83, 'Informatics Practices': 65, 'English': 101, 'Hindi': 102, 'Sanskrit':
122}
Key 1
Key 2
Key 3
Key 4
value 3
value 4
value 1
value 2
CHARACTERISTICS OF DICTIONARY
7. Internally Dictionary is stored as mapping: Internally the key:value pairs of a dictionary
are associated with one another with some internal function(called hash-
function-algorithm to map and link a key with a stored value). This way of linking is
called mapping.
Hash Function
Internally Keys are mapped with values using hash function
WORKING WITH DICTIONARY
Adding Key:value pairs to an Empty Dictionary : In this method first we create a
empty dictionary and then keys and values are added to it.
>>> purse = { }
>>> purse['money'] = 12
>>> purse['candy'] = 3
>>> purse['tissues'] = 75
>>> print(purse)
{'money': 12, 'tissues': 75, 'candy': 3}
>>> print(purse['candy'])
3
>>> purse['candy'] = purse['candy'] + 2
>>> print(purse)
{'money': 12, 'tissues': 75, 'candy': 5}
WORKING WITH DICTIONARY
Multiple ways of creating Dictionary: Various ways are as below:
Creating a dictionary from name and values pairs: Using dict() constructor we an create dictionary
from any key :value pair.
>>> Emp1=dict(name="Prakash",Subject="Computer",School="HFC Barauni")
>>> Emp1
{'name': 'Prakash', 'Subject': 'Computer', 'School': 'HFC Barauni'}
or specify comma separated key:value pairs
>>> Emp2=dict({"name":"Rishi","Subject":"Informatics Practices","School":"KV Muzaffarpur FS"})
>>> Emp2
{'name': 'Rishi', 'Subject': 'Informatics Practices', 'School': 'KV Muzaffarpur FS'}
(d) Specify Keys Separately and corresponding values separately:
>>> EMP4=dict(zip(("name","Subject","School"),("R K Tiwari","IP","KV Kishanganj")))
>>> EMP4
{'name': 'R K Tiwari', 'Subject': 'IP', 'School': 'KV Kishanganj'}
zip() function clubs first key with first value, second key with second value and so on.
WORKING WITH DICTIONARY
1. Multiple ways of creating Dictionary: Various ways are as below:
(e) Specify Keys:value pairs Separately in the form of sequence :
Using List
>>> Emp=dict([ ["name","Jaykank"], ["Subject","Computer Science"], ["School","KV
Danapur Cantt"]])
>>> Emp
{'name': 'Jaykank', 'Subject': 'Computer Science', 'School': 'KV Danapur Cantt'}
Using Tuples
>>> Emp1=dict((("name","Srwari Begum"),("Subject","Computer Science"),("School","KV
Bailey Road")))
>>> Emp1
{'name': 'Srwari Begum', 'Subject': 'Computer Science', 'School': 'KV Bailey Road'}
Note: Using dict() method to create a dictionary takes longer time compared
to traditional method of enclosing values in { }. Thus it should be avoided until it
becomes a necessity.
ADDING ELEMENTS TO DICTIONARY
We can add new elements (kye:value) to a dictionary using assignment as
per syntax given below:
<dictionary>[<key>]=<value>
>>> Subject={"Computer":"083","Informatics Practices":"065"}
>>> Subject
{'Computer': '083', 'Informatics Practices': '065'}
>>> Subject["English"]="101"
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': '101'}
UPDATING ELEMENTS OF DICTIONARY
We can update value of an existing element (kye:value) to a dictionary using
assignment as per syntax given below:
<dictionary>[<existing key>]=<new value>
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': '101'}
>>> Subject["Enlgsih"]="001"
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': ‘001',}
Note: To add and to update the syntax is exactly same but in case adding the Key must be
a new unique key and for updating the key must be an existing key and the value will be
a new value by which the key value have to be changed.
DELETING ELEMENTS FROM
DICTIONARY
We can delete element from a dictionary using following two ways
(a) del <dictionary>[<key>]
(b) <dictionary>.pop(<key>)
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': ‘001',}
>>> del Subject["English"]
>>> Subject
{'Computer': '083', 'Informatics Practices': '065'}
>>> Subject.pop("Computer")
'083‘ # popped key value is returned by pop() function which is displayed
>>> Subject
{'Informatics Practices': '065', 'English': '001'}
CHECKING FOR EXISTING OF A KEY IN DICTIONARY
Usual Membership operator in and not in work with dictionary as well to
check for the presence / absence of a key in the dictionary.
>>> emp={'age':25,"Salary":10000,"name":"sanjay"}
>>> "age“ in emp
True
>>> "name" in emp
True
>>> "basic" in emp
False
>>> "basic" not in emp
True
But if we want to check whether a value is present in a dictionary (called
reverse lookup) we need to write proper code.
CHECKING FOR VALUE OF EXISTING KEY IN
DICTIONARY
The following code can be used to check a value in the dictionary.
dict1={0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five"} ans='y'
while ans=='y' or ans=='Y':
val=input("Enter Vlue: ") print("Value
",val, end=" ") for k in dict1:
if dict1[k] == val: print("Exists at
",k) break;
else:
print("Not Found")
ans=input("Want to check another
value:(y/n)? :- ")
DICTIONARY FUNCTIONS AND METHODS
clear() function removes all the elements of the dictionary but the dictinary object still
remains in memory.
del command used with dictionary delete dictionary object also,
SN METHODS PURPOSE SYNTAX AND EXAMPLE
01. len() Returns length of dictionary len<dictionary>
Example
>>> employee={"Name":"B Kumar","Salary":10000,"Age":45}
>>> employee
{'Name': 'B Kumar', 'Salary': 10000, 'Age': 45}
>>> len(employee)
3
02. clear() Removes all elements of a
list
<dictionary>.clear()
>>> employee={"Name":"B Kumar","Salary":10000,"Age":45}
>>> employee
{'Name': 'B Kumar', 'Salary': 10000, 'Age': 45}
>>> employee.clear()
>>> employee
{}
DICTIONARY FUNCTIONS AND METHODS
SN METHODS PURPOSE SYNTAX AND EXAMPLE
03. get( ) We can get the item with the
given key similar to
dictionary[key]
<dictionary>.get()
Example
>>> Subject={"Computer":"083","Informatics
Practices":"065"}
>>> Subject.get("Computer")
'083'
04. items() Returns all of the items in
the dictionary as a sequence
<dictionary>.items()
>>> Subject={"Computer":"083","Informatics
Practices":"065"}
>>>subject
>>> Subject
{'Computer': '083', 'Informatics Practices':
'065'}
>>> Mylist=Subject.items()
>>> Mylist
dict_items([('Computer', '083'), ('Informatics Practices',
'065')])
DICTIONARY FUNCTIONS AND METHODS
SN METHODS PURPOSE SYNTAX AND EXAMPLE
05. keys() This method returns all
the keys in the dictionary
as a sequence (in the form
of list)
<dictionary>.keys()
Example
>>> Subject={"Computer":'083',"IP":'065',"Math":'041'}
>>> Subject
{'Computer': '083', 'IP': '065', 'Math': '041'}
>>> Subject.keys()
dict_keys(['Computer', 'IP', 'Math'])
06. values() This method returns all
the values in the
dictionary as a sequence
(in the form of list)
>>> Subject={"Computer":'083',"IP":'065',"Math":'041'}
>>> Subject
{'Computer': '083', 'IP': '065', 'Math': '041'}
>>> Subject.values()
dict_values(['083', '065', '041'])
DICTIONARY FUNCTIONS AND METHODS
SN METHODS PURPOSE SYNTAX AND EXAMPLE
07. update() Merges {key:value} pairs
from the new dictionary into
the existing dictionary,
adding or replacing as
needed. The items in the
new dictionary are added to
the old one override any
items already there with the
same keys.
dictionary_to_be_updated.update(dictionary_which_to_be
_updated)
>>> Subject={"Computer":'083',"IP":'065',"Math":'041'}
>>> Subject
{'Computer': '083', 'IP': '065', 'Math': '041'}
>>>
Science={"Physics":"042","Chemistry":"043","Math":"041"}
>>> Science
{'Physics': '042', 'Chemistry': '043', 'Math': '041'}
>>> Subject.update(Science)
>>> Subject
{'Computer': '083', 'IP': '065', 'Math': '041', 'Physics': '042',
'Chemistry': '043'}
Comparing Lists and Dictionaries
Dictionaries are like lists except that they use keys instead of
numbers to look up values
>>> lst = list()
>>> lst.append(21)
>>> lst.append(183)
>>> print(lst)
[21, 183]
>>> lst[0] = 23
>>> print(lst)
[23, 183]
>>> ddd = dict()
>>> ddd['age'] = 21
>>> ddd['course'] = 182
>>> print(ddd)
{'course': 182, 'age': 21}
>>> ddd['age'] = 23
>>> print(ddd)
{'course': 182, 'age': 23}
When We See a New Name
When we encounter a new name, we need to add a new entry in the
dictionary and if this the second or later time we have seen the
name, we simply add one to the count in the dictionary under that
name
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
if name not in counts:
counts[name] = 1
else :
counts[name] = counts[name] + 1
print(counts)
{'csev': 2, 'zqian': 1, 'cwen': 2}
The get Method for Dictionaries
The pattern of checking to see if a key
is already in a dictionary and
assuming a default value if the key is
not there is so common that there is a
method called get() that does this for
us
if name in counts:
x = counts[name]
else :
x = 0
x = counts.get(name, 0)
Default value if key does not exist
(and no Traceback). {'csev': 2, 'zqian': 1, 'cwen': 2}
Simplified Counting with get()
We can use get() and provide a default value of zero when the key
is not yet in the dictionary - and then just add one
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
counts[name] = counts.get(name, 0) + 1
print(counts)
Default {'csev': 2, 'zqian': 1, 'cwen': 2}
http://www.youtube.com/watch?v=EHJ9uYx5L58
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
counts[name] = counts.get(name, 0) + 1
print(counts)
Simplified Counting with get()
Counting Words in Text
Writing programs (or programming) is a very creative and rewarding activity. You can write
programs for many reasons ranging from making your living to solving a difficult data analysis
problem to having fun to helping someone else solve a problem. This book assumes that
everyone needs to know how to program and that once you know how to program, you will figure
out what you want to do with your newfound skills.
We are surrounded in our daily lives with computers ranging from laptops to cell phones. We can
think of these computers as our “personal assistants” who can take care of many things on our
behalf. The hardware in our current-day computers is essentially built to continuously ask us the
question, “What would you like me to do next?”
Our computers are fast and have vast amounts of memory and could be very helpful to us if we
only knew the language to speak to explain to the computer what we would like it to do next. If
we knew this language we could tell the computer to do tasks on our behalf that were repetitive.
Interestingly, the kinds of things computers can do best are often the kinds of things that we
humans find boring and mind-numbing.
Counting Pattern
counts = dict()
print('Enter a line of text:')
line = input('')
words = line.split()
print('Words:', words)
print('Counting...')
for word in words:
counts[word] = counts.get(word,0) + 1
print('Counts', counts)
The general pattern to count the
words in a line of text is to split
the line into words, then loop
through the words and use a
dictionary to track the count of
each word independently.
python wordcount.py
Enter a line of text:
the clown ran after the car and the car ran into the
tent and the tent fell down on the clown and the car
Words: ['the', 'clown', 'ran', 'after', 'the', 'car',
'and', 'the', 'car', 'ran', 'into', 'the', 'tent',
'and', 'the', 'tent', 'fell', 'down', 'on', 'the',
'clown', 'and', 'the', 'car']
Counting…
Counts {'and': 3, 'on': 1, 'ran': 2, 'car': 3, 'into':
1, 'after': 1, 'clown': 2, 'down': 1, 'fell': 1, 'the':
7, 'tent': 2}
http://www.flickr.com/photos/71502646@N00/2526007974/
counts = dict()
line = input('Enter a line of text:')
words = line.split()
print('Words:', words)
print('Counting...’)
for word in words:
counts[word] = counts.get(word,0) + 1
print('Counts', counts)
python wordcount.py
Enter a line of text:
the clown ran after the car and the car ran
into the tent and the tent fell down on the
clown and the car
Words: ['the', 'clown', 'ran', 'after', 'the', 'car',
'and', 'the', 'car', 'ran', 'into', 'the', 'tent', 'and',
'the', 'tent', 'fell', 'down', 'on', 'the', 'clown',
'and', 'the', 'car']
Counting...
Counts {'and': 3, 'on': 1, 'ran': 2, 'car': 3,
'into': 1, 'after': 1, 'clown': 2, 'down': 1, 'fell':
1, 'the': 7, 'tent': 2}
Definite Loops and Dictionaries
Even though dictionaries are not stored in order, we can write a for
loop that goes through all the entries in a dictionary - actually it
goes through all of the keys in the dictionary and looks up the
values
>>> counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> for key in counts:
... print(key, counts[key])
...
jan 100
chuck 1
fred 42
>>>
Retrieving Lists of Keys and Values
You can get a list
of keys, values, or
items (both) from
a dictionary
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan':
100}
>>> print(list(jjj))
['jan', 'chuck', 'fred']
>>> print(jjj.keys())
['jan', 'chuck', 'fred']
>>> print(jjj.values())
[100, 1, 42]
>>> print(jjj.items())
[('jan', 100), ('chuck', 1), ('fred', 42)]
>>>
What is a “tuple”? - coming soon...
Bonus: Two Iteration Variables!
• We loop through the
key-value pairs in a
dictionary using *two*
iteration variables
• Each iteration, the first
variable is the key and
the second variable is
the corresponding
value for the key
jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
for aaa,bbb in jjj.items() :
print(aaa, bbb)
jan 100
chuck 1
fred 42 [chuck] 1
[fred] 42
aaa bbb
[jan] 100
name = input('Enter file:')
handle = open(name)
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
python words.py
Enter file: clown.txt
the 7
python words.py
Enter file: words.txt
to 16
Using two nested loops

More Related Content

Similar to PYTHON Data structures Fundamentals: DICTIONARIES (20)

PPTX
Dictionary.pptx
RishuVerma34
 
PPTX
Python dictionary
eman lotfy
 
PPTX
Untitled dictionary in python program .pdf.pptx
SnehasisGhosh10
 
PPTX
Python dictionary
Sagar Kumar
 
PPTX
Dictionary in python
vikram mahendra
 
PPTX
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
PPTX
Dictionaries in Python programming language
ssuserbad56d
 
PPTX
Dictionaries.pptx
akshat205573
 
PPTX
Python Lecture 10
Inzamam Baig
 
PDF
Python Dictionary
Soba Arjun
 
PPTX
Ch_13_Dictionary.pptx
HarishParthasarathy4
 
PPTX
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
pawankamal3
 
PPTX
Chapter 16 Dictionaries
Praveen M Jigajinni
 
PPTX
DICTIONARIES TUTORIALS FOR ADVANCED LEARNING OF YTHON PROGRAMMING
examcelldavrng
 
DOC
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
PPTX
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
PDF
ESIT135 Problem Solving Using Python Notes of Unit-3
prasadmutkule1
 
PPTX
Unit4-Basic Concepts and methods of Dictionary.pptx
SwapnaliGawali5
 
Dictionary.pptx
RishuVerma34
 
Python dictionary
eman lotfy
 
Untitled dictionary in python program .pdf.pptx
SnehasisGhosh10
 
Python dictionary
Sagar Kumar
 
Dictionary in python
vikram mahendra
 
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
Dictionaries in Python programming language
ssuserbad56d
 
Dictionaries.pptx
akshat205573
 
Python Lecture 10
Inzamam Baig
 
Python Dictionary
Soba Arjun
 
Ch_13_Dictionary.pptx
HarishParthasarathy4
 
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
pawankamal3
 
Chapter 16 Dictionaries
Praveen M Jigajinni
 
DICTIONARIES TUTORIALS FOR ADVANCED LEARNING OF YTHON PROGRAMMING
examcelldavrng
 
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
ESIT135 Problem Solving Using Python Notes of Unit-3
prasadmutkule1
 
Unit4-Basic Concepts and methods of Dictionary.pptx
SwapnaliGawali5
 

More from KanadamKarteekaPavan1 (8)

PPT
Market research analysis in Fundamentals of IDE workshop
KanadamKarteekaPavan1
 
PPTX
Vehicle Number Plate Detection_ppt_Rajeev.pptx
KanadamKarteekaPavan1
 
PPTX
Python Fundamental Data structures: Dictionaries
KanadamKarteekaPavan1
 
PPTX
Graphic programming using Turtle class in Python
KanadamKarteekaPavan1
 
PPTX
Prime finding- sieve Method- Finding Anagrams numpy
KanadamKarteekaPavan1
 
PPTX
Varioius types of Neural Networks- An introduction
KanadamKarteekaPavan1
 
PPTX
Introduction to Soft Computing - Presentation
KanadamKarteekaPavan1
 
PPT
Chapter-1.ppt
KanadamKarteekaPavan1
 
Market research analysis in Fundamentals of IDE workshop
KanadamKarteekaPavan1
 
Vehicle Number Plate Detection_ppt_Rajeev.pptx
KanadamKarteekaPavan1
 
Python Fundamental Data structures: Dictionaries
KanadamKarteekaPavan1
 
Graphic programming using Turtle class in Python
KanadamKarteekaPavan1
 
Prime finding- sieve Method- Finding Anagrams numpy
KanadamKarteekaPavan1
 
Varioius types of Neural Networks- An introduction
KanadamKarteekaPavan1
 
Introduction to Soft Computing - Presentation
KanadamKarteekaPavan1
 
Chapter-1.ppt
KanadamKarteekaPavan1
 
Ad

Recently uploaded (20)

PDF
InformaticsPractices-MS - Google Docs.pdf
seshuashwin0829
 
PDF
Optimizing Large Language Models with vLLM and Related Tools.pdf
Tamanna36
 
PDF
Data Science Course Certificate by Sigma Software University
Stepan Kalika
 
PPTX
Powerful Uses of Data Analytics You Should Know
subhashenia
 
PDF
1750162332_Snapshot-of-Indias-oil-Gas-data-May-2025.pdf
sandeep718278
 
PPTX
办理学历认证InformaticsLetter新加坡英华美学院毕业证书,Informatics成绩单
Taqyea
 
PPTX
How to Add Columns and Rows in an R Data Frame
subhashenia
 
PDF
Unlocking Insights: Introducing i-Metrics Asia-Pacific Corporation and Strate...
Janette Toral
 
PDF
apidays Singapore 2025 - Building a Federated Future, Alex Szomora (GSMA)
apidays
 
PDF
apidays Singapore 2025 - Streaming Lakehouse with Kafka, Flink and Iceberg by...
apidays
 
PPTX
在线购买英国本科毕业证苏格兰皇家音乐学院水印成绩单RSAMD学费发票
Taqyea
 
PPT
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
PDF
SQL for Accountants and Finance Managers
ysmaelreyes
 
PPTX
Feb 2021 Ransomware Recovery presentation.pptx
enginsayin1
 
PPTX
big data eco system fundamentals of data science
arivukarasi
 
PDF
Using AI/ML for Space Biology Research
VICTOR MAESTRE RAMIREZ
 
PDF
apidays Singapore 2025 - How APIs can make - or break - trust in your AI by S...
apidays
 
PPTX
b6057ea5-8e8c-4415-90c0-ed8e9666ffcd.pptx
Anees487379
 
PPT
tuberculosiship-2106031cyyfuftufufufivifviviv
AkshaiRam
 
PDF
The Best NVIDIA GPUs for LLM Inference in 2025.pdf
Tamanna36
 
InformaticsPractices-MS - Google Docs.pdf
seshuashwin0829
 
Optimizing Large Language Models with vLLM and Related Tools.pdf
Tamanna36
 
Data Science Course Certificate by Sigma Software University
Stepan Kalika
 
Powerful Uses of Data Analytics You Should Know
subhashenia
 
1750162332_Snapshot-of-Indias-oil-Gas-data-May-2025.pdf
sandeep718278
 
办理学历认证InformaticsLetter新加坡英华美学院毕业证书,Informatics成绩单
Taqyea
 
How to Add Columns and Rows in an R Data Frame
subhashenia
 
Unlocking Insights: Introducing i-Metrics Asia-Pacific Corporation and Strate...
Janette Toral
 
apidays Singapore 2025 - Building a Federated Future, Alex Szomora (GSMA)
apidays
 
apidays Singapore 2025 - Streaming Lakehouse with Kafka, Flink and Iceberg by...
apidays
 
在线购买英国本科毕业证苏格兰皇家音乐学院水印成绩单RSAMD学费发票
Taqyea
 
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
SQL for Accountants and Finance Managers
ysmaelreyes
 
Feb 2021 Ransomware Recovery presentation.pptx
enginsayin1
 
big data eco system fundamentals of data science
arivukarasi
 
Using AI/ML for Space Biology Research
VICTOR MAESTRE RAMIREZ
 
apidays Singapore 2025 - How APIs can make - or break - trust in your AI by S...
apidays
 
b6057ea5-8e8c-4415-90c0-ed8e9666ffcd.pptx
Anees487379
 
tuberculosiship-2106031cyyfuftufufufivifviviv
AkshaiRam
 
The Best NVIDIA GPUs for LLM Inference in 2025.pdf
Tamanna36
 
Ad

PYTHON Data structures Fundamentals: DICTIONARIES

  • 2. A Story of Two Collections.. • List - A linear collection of values that stay in order • Dictionary - A “bag” of values, each with its own label
  • 3. INTRODUCTION • Dictionary are mutable, unordered collection with elements in the form of a key:value pairs that associate keys to values. • Rather than index associated with lists, tuples and strings,a dictionary has key associated with values. • It is just like English Dictionary where meaning is associated with a word (Key). • Dictionaries are containers that associate keys to values. • With list, tuples and strings we need to know the index of individual element to access but with Dictionaries user need to search value based on key.
  • 4. >>>Month={“January":31,"February":28,"March":31,"April":30, "May":31,"June":30,"July":31,"August":31,"September":30,"October":31," November":30, "December":31} >>> teacher={'kkp':'9885139413','Prakash':'8604774180'} Notice that: 1. Curly braces mark the beginning and end of the dictionary 2. Each entry (key:value) consists of a pair separated by a colon. The key and corresponding value is given by writing colon(:) between them. 3. The key:value pairs are separated by comma. Internally dictionaries are indexed (i.e.) arranged on the basis of keys. CREATING AND ACCESSING LISTS
  • 5. SOME MORE DICTIONARY DECLRATION Emptydisctionary={ } >>>daynumberofweek={"Monday":1, "Tuesday":2, "Wednesday":3, "Thursday":4,"Friday":5,"Saturday":6,"Sunday":7} >>> subjectandcode={"Physics":42,"Chemistry":43, "Mathematics":41, "Biology":44,"ComputerScience":83,"Informatics Practices":65,"English":101,"Hindi":2} Note: • Dictionaries are also called Associative Arrays or mappings or hashes. • Keys of a dictionaries must be of immutable type such as Python string, Number, a tuple (containing only immutable entry) but list which is mutable cannot be used as keys of a dictionary. >>>dict2={[2,3]:”abc”} #TypeError: Un-sharable Type ‘list’
  • 6. ACCESSING OF A DICTIONARY Its general syntax is dictionaryname<“key"> EXAMPLE: >>> subjectandcode["Hindi"] 2 >>> subjectandcode["Computer Science"] 83 >>> subjectandcode["Informatics Practices"] 65
  • 7. ACCESSING ENTIRE DICTIONARY >>>dictionaryname • Mentioning only the dictionary name without any key prints the entire dictionary. • If the key in square bracket is used along with dictionaryname produces the value that matches the key otherwise error is displayed. Example: >>> subjectandcode {'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44, 'Computer Science': 83, 'Informatics Practices': 65, 'English': 101, 'Hindi': 2} >>> subjectandcode["Hindi"] 2
  • 8. • A dictionary operation that takes a key and finds the corresponding value is called lookup. • To access a particular value of the dictionary the key is provided in square bracket is in double quote i.e. of string type. • In python the elements (key:value pairs) are unordered. It means one can not access elements as per specific order. • References of keys and values are stored in dictionaries. • Dictionaries are unordered set of elements, the printed order of elements may or may not be in the order in which we have stored them in the dictionary.
  • 9. Access Dictionary Keys:Value one by one through Loop >>> for subject in subjectandcode: print(subject,":",subjectandcode[subject]) Physics : 42 Chemistry : 43 Mathematics : 41 Biology : 44 Computer Science : 83 Informatics Practices : 65 English : 101 Hindi : 2
  • 10. Accessing Keys and Values >>> subjectandcode.keys() dict_keys(['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer Science', 'Informatics Practices', 'English', 'Hindi']) >>> subjectandcode.values() dict_values([42, 43, 41, 44, 83, 65,101, 2]) It can be converted in list as below >>> list(subjectandcode.keys()) ['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer Science', 'Informatics Practices', 'English', 'Hindi'] >>> list(subjectandcode.values()) [42, 43, 41, 44, 83, 65, 101, 2]
  • 11. Accessing Keys and Values The keys of Dictionaries converted into list can be stored in a list variable. >>> Subject=list(subjectandcode.keys()) >>>Subject ['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer Science', 'Informatics Practices', 'English', 'Hindi'] >>> SubjectCode=list(subjectandcode.values()) >>>SubjectCode [42, 43, 41, 44, 83, 65, 101, 2]
  • 12. CHARACTERISTICS OF DICTIONARY • Dictionary is mutable like list. Except this there is no similarity with list. It has following attributes: 1. Unordered set: Dictionary is an unordered set of keys:value pairs. Its value can contain references to any type of object. 2. Not a sequence: Unlike string,, lists and tuples a dictionary is not a sequence because it is unordered The sequence are indexed by range or ordinal numbers. Hence they are ordered but dictionaries are unordered collection . 3. Indexed by Keys and not Numbers: Dictionaries are indexed by keys. According to Python, a key can be ”any non-mutable type”. Since Strings and Numbers are non mutable it can be used as keys. Tuple if containing immutable objects (integers and strings), can be used as keys. A value in a dictionary can be of any type and type can be mixed within one dictionary.
  • 13. CHARACTERISTICS OF DICTIONARY 4. Keys must be unique: Each of the keys within a dictionary must be unique. Since keys are used to identify values in a dictionary, there can not be duplicate keys in a dictionary. However two unique keys have same value. 5. Mutable: Like list, dictionaries are also mutable. We can change the value of a certain key “in place” using the assignment statement as per following syntax <dictionary>[<key>]=<value> >>> subjectandcode["Hindi"]=102 >>> subjectandcode {'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44, 'Computer Science': 83, 'Informatics Practices': 65, 'English': 101, 'Hindi': 102}
  • 14. CHARACTERISTICS OF DICTIONARY 6. We can add new key:value pair to existing dictionary:Using following syntax a new Key:value pair can be added to dictionary. dictionary[“new”]=“a new pair is added” >>> subjectandcode["Sanskrit"]=122 >>> subjectandcode {'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44, 'Computer Science': 83, 'Informatics Practices': 65, 'English': 101, 'Hindi': 102, 'Sanskrit': 122}
  • 15. Key 1 Key 2 Key 3 Key 4 value 3 value 4 value 1 value 2 CHARACTERISTICS OF DICTIONARY 7. Internally Dictionary is stored as mapping: Internally the key:value pairs of a dictionary are associated with one another with some internal function(called hash- function-algorithm to map and link a key with a stored value). This way of linking is called mapping. Hash Function Internally Keys are mapped with values using hash function
  • 16. WORKING WITH DICTIONARY Adding Key:value pairs to an Empty Dictionary : In this method first we create a empty dictionary and then keys and values are added to it. >>> purse = { } >>> purse['money'] = 12 >>> purse['candy'] = 3 >>> purse['tissues'] = 75 >>> print(purse) {'money': 12, 'tissues': 75, 'candy': 3} >>> print(purse['candy']) 3 >>> purse['candy'] = purse['candy'] + 2 >>> print(purse) {'money': 12, 'tissues': 75, 'candy': 5}
  • 17. WORKING WITH DICTIONARY Multiple ways of creating Dictionary: Various ways are as below: Creating a dictionary from name and values pairs: Using dict() constructor we an create dictionary from any key :value pair. >>> Emp1=dict(name="Prakash",Subject="Computer",School="HFC Barauni") >>> Emp1 {'name': 'Prakash', 'Subject': 'Computer', 'School': 'HFC Barauni'} or specify comma separated key:value pairs >>> Emp2=dict({"name":"Rishi","Subject":"Informatics Practices","School":"KV Muzaffarpur FS"}) >>> Emp2 {'name': 'Rishi', 'Subject': 'Informatics Practices', 'School': 'KV Muzaffarpur FS'} (d) Specify Keys Separately and corresponding values separately: >>> EMP4=dict(zip(("name","Subject","School"),("R K Tiwari","IP","KV Kishanganj"))) >>> EMP4 {'name': 'R K Tiwari', 'Subject': 'IP', 'School': 'KV Kishanganj'} zip() function clubs first key with first value, second key with second value and so on.
  • 18. WORKING WITH DICTIONARY 1. Multiple ways of creating Dictionary: Various ways are as below: (e) Specify Keys:value pairs Separately in the form of sequence : Using List >>> Emp=dict([ ["name","Jaykank"], ["Subject","Computer Science"], ["School","KV Danapur Cantt"]]) >>> Emp {'name': 'Jaykank', 'Subject': 'Computer Science', 'School': 'KV Danapur Cantt'} Using Tuples >>> Emp1=dict((("name","Srwari Begum"),("Subject","Computer Science"),("School","KV Bailey Road"))) >>> Emp1 {'name': 'Srwari Begum', 'Subject': 'Computer Science', 'School': 'KV Bailey Road'} Note: Using dict() method to create a dictionary takes longer time compared to traditional method of enclosing values in { }. Thus it should be avoided until it becomes a necessity.
  • 19. ADDING ELEMENTS TO DICTIONARY We can add new elements (kye:value) to a dictionary using assignment as per syntax given below: <dictionary>[<key>]=<value> >>> Subject={"Computer":"083","Informatics Practices":"065"} >>> Subject {'Computer': '083', 'Informatics Practices': '065'} >>> Subject["English"]="101" >>> Subject {'Computer': '083', 'Informatics Practices': '065', 'English': '101'}
  • 20. UPDATING ELEMENTS OF DICTIONARY We can update value of an existing element (kye:value) to a dictionary using assignment as per syntax given below: <dictionary>[<existing key>]=<new value> >>> Subject {'Computer': '083', 'Informatics Practices': '065', 'English': '101'} >>> Subject["Enlgsih"]="001" >>> Subject {'Computer': '083', 'Informatics Practices': '065', 'English': ‘001',} Note: To add and to update the syntax is exactly same but in case adding the Key must be a new unique key and for updating the key must be an existing key and the value will be a new value by which the key value have to be changed.
  • 21. DELETING ELEMENTS FROM DICTIONARY We can delete element from a dictionary using following two ways (a) del <dictionary>[<key>] (b) <dictionary>.pop(<key>) >>> Subject {'Computer': '083', 'Informatics Practices': '065', 'English': ‘001',} >>> del Subject["English"] >>> Subject {'Computer': '083', 'Informatics Practices': '065'} >>> Subject.pop("Computer") '083‘ # popped key value is returned by pop() function which is displayed >>> Subject {'Informatics Practices': '065', 'English': '001'}
  • 22. CHECKING FOR EXISTING OF A KEY IN DICTIONARY Usual Membership operator in and not in work with dictionary as well to check for the presence / absence of a key in the dictionary. >>> emp={'age':25,"Salary":10000,"name":"sanjay"} >>> "age“ in emp True >>> "name" in emp True >>> "basic" in emp False >>> "basic" not in emp True But if we want to check whether a value is present in a dictionary (called reverse lookup) we need to write proper code.
  • 23. CHECKING FOR VALUE OF EXISTING KEY IN DICTIONARY The following code can be used to check a value in the dictionary. dict1={0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five"} ans='y' while ans=='y' or ans=='Y': val=input("Enter Vlue: ") print("Value ",val, end=" ") for k in dict1: if dict1[k] == val: print("Exists at ",k) break; else: print("Not Found") ans=input("Want to check another value:(y/n)? :- ")
  • 24. DICTIONARY FUNCTIONS AND METHODS clear() function removes all the elements of the dictionary but the dictinary object still remains in memory. del command used with dictionary delete dictionary object also, SN METHODS PURPOSE SYNTAX AND EXAMPLE 01. len() Returns length of dictionary len<dictionary> Example >>> employee={"Name":"B Kumar","Salary":10000,"Age":45} >>> employee {'Name': 'B Kumar', 'Salary': 10000, 'Age': 45} >>> len(employee) 3 02. clear() Removes all elements of a list <dictionary>.clear() >>> employee={"Name":"B Kumar","Salary":10000,"Age":45} >>> employee {'Name': 'B Kumar', 'Salary': 10000, 'Age': 45} >>> employee.clear() >>> employee {}
  • 25. DICTIONARY FUNCTIONS AND METHODS SN METHODS PURPOSE SYNTAX AND EXAMPLE 03. get( ) We can get the item with the given key similar to dictionary[key] <dictionary>.get() Example >>> Subject={"Computer":"083","Informatics Practices":"065"} >>> Subject.get("Computer") '083' 04. items() Returns all of the items in the dictionary as a sequence <dictionary>.items() >>> Subject={"Computer":"083","Informatics Practices":"065"} >>>subject >>> Subject {'Computer': '083', 'Informatics Practices': '065'} >>> Mylist=Subject.items() >>> Mylist dict_items([('Computer', '083'), ('Informatics Practices', '065')])
  • 26. DICTIONARY FUNCTIONS AND METHODS SN METHODS PURPOSE SYNTAX AND EXAMPLE 05. keys() This method returns all the keys in the dictionary as a sequence (in the form of list) <dictionary>.keys() Example >>> Subject={"Computer":'083',"IP":'065',"Math":'041'} >>> Subject {'Computer': '083', 'IP': '065', 'Math': '041'} >>> Subject.keys() dict_keys(['Computer', 'IP', 'Math']) 06. values() This method returns all the values in the dictionary as a sequence (in the form of list) >>> Subject={"Computer":'083',"IP":'065',"Math":'041'} >>> Subject {'Computer': '083', 'IP': '065', 'Math': '041'} >>> Subject.values() dict_values(['083', '065', '041'])
  • 27. DICTIONARY FUNCTIONS AND METHODS SN METHODS PURPOSE SYNTAX AND EXAMPLE 07. update() Merges {key:value} pairs from the new dictionary into the existing dictionary, adding or replacing as needed. The items in the new dictionary are added to the old one override any items already there with the same keys. dictionary_to_be_updated.update(dictionary_which_to_be _updated) >>> Subject={"Computer":'083',"IP":'065',"Math":'041'} >>> Subject {'Computer': '083', 'IP': '065', 'Math': '041'} >>> Science={"Physics":"042","Chemistry":"043","Math":"041"} >>> Science {'Physics': '042', 'Chemistry': '043', 'Math': '041'} >>> Subject.update(Science) >>> Subject {'Computer': '083', 'IP': '065', 'Math': '041', 'Physics': '042', 'Chemistry': '043'}
  • 28. Comparing Lists and Dictionaries Dictionaries are like lists except that they use keys instead of numbers to look up values >>> lst = list() >>> lst.append(21) >>> lst.append(183) >>> print(lst) [21, 183] >>> lst[0] = 23 >>> print(lst) [23, 183] >>> ddd = dict() >>> ddd['age'] = 21 >>> ddd['course'] = 182 >>> print(ddd) {'course': 182, 'age': 21} >>> ddd['age'] = 23 >>> print(ddd) {'course': 182, 'age': 23}
  • 29. When We See a New Name When we encounter a new name, we need to add a new entry in the dictionary and if this the second or later time we have seen the name, we simply add one to the count in the dictionary under that name counts = dict() names = ['csev', 'cwen', 'csev', 'zqian', 'cwen'] for name in names : if name not in counts: counts[name] = 1 else : counts[name] = counts[name] + 1 print(counts) {'csev': 2, 'zqian': 1, 'cwen': 2}
  • 30. The get Method for Dictionaries The pattern of checking to see if a key is already in a dictionary and assuming a default value if the key is not there is so common that there is a method called get() that does this for us if name in counts: x = counts[name] else : x = 0 x = counts.get(name, 0) Default value if key does not exist (and no Traceback). {'csev': 2, 'zqian': 1, 'cwen': 2}
  • 31. Simplified Counting with get() We can use get() and provide a default value of zero when the key is not yet in the dictionary - and then just add one counts = dict() names = ['csev', 'cwen', 'csev', 'zqian', 'cwen'] for name in names : counts[name] = counts.get(name, 0) + 1 print(counts) Default {'csev': 2, 'zqian': 1, 'cwen': 2}
  • 32. http://www.youtube.com/watch?v=EHJ9uYx5L58 counts = dict() names = ['csev', 'cwen', 'csev', 'zqian', 'cwen'] for name in names : counts[name] = counts.get(name, 0) + 1 print(counts) Simplified Counting with get()
  • 34. Writing programs (or programming) is a very creative and rewarding activity. You can write programs for many reasons ranging from making your living to solving a difficult data analysis problem to having fun to helping someone else solve a problem. This book assumes that everyone needs to know how to program and that once you know how to program, you will figure out what you want to do with your newfound skills. We are surrounded in our daily lives with computers ranging from laptops to cell phones. We can think of these computers as our “personal assistants” who can take care of many things on our behalf. The hardware in our current-day computers is essentially built to continuously ask us the question, “What would you like me to do next?” Our computers are fast and have vast amounts of memory and could be very helpful to us if we only knew the language to speak to explain to the computer what we would like it to do next. If we knew this language we could tell the computer to do tasks on our behalf that were repetitive. Interestingly, the kinds of things computers can do best are often the kinds of things that we humans find boring and mind-numbing.
  • 35. Counting Pattern counts = dict() print('Enter a line of text:') line = input('') words = line.split() print('Words:', words) print('Counting...') for word in words: counts[word] = counts.get(word,0) + 1 print('Counts', counts) The general pattern to count the words in a line of text is to split the line into words, then loop through the words and use a dictionary to track the count of each word independently.
  • 36. python wordcount.py Enter a line of text: the clown ran after the car and the car ran into the tent and the tent fell down on the clown and the car Words: ['the', 'clown', 'ran', 'after', 'the', 'car', 'and', 'the', 'car', 'ran', 'into', 'the', 'tent', 'and', 'the', 'tent', 'fell', 'down', 'on', 'the', 'clown', 'and', 'the', 'car'] Counting… Counts {'and': 3, 'on': 1, 'ran': 2, 'car': 3, 'into': 1, 'after': 1, 'clown': 2, 'down': 1, 'fell': 1, 'the': 7, 'tent': 2} http://www.flickr.com/photos/71502646@N00/2526007974/
  • 37. counts = dict() line = input('Enter a line of text:') words = line.split() print('Words:', words) print('Counting...’) for word in words: counts[word] = counts.get(word,0) + 1 print('Counts', counts) python wordcount.py Enter a line of text: the clown ran after the car and the car ran into the tent and the tent fell down on the clown and the car Words: ['the', 'clown', 'ran', 'after', 'the', 'car', 'and', 'the', 'car', 'ran', 'into', 'the', 'tent', 'and', 'the', 'tent', 'fell', 'down', 'on', 'the', 'clown', 'and', 'the', 'car'] Counting... Counts {'and': 3, 'on': 1, 'ran': 2, 'car': 3, 'into': 1, 'after': 1, 'clown': 2, 'down': 1, 'fell': 1, 'the': 7, 'tent': 2}
  • 38. Definite Loops and Dictionaries Even though dictionaries are not stored in order, we can write a for loop that goes through all the entries in a dictionary - actually it goes through all of the keys in the dictionary and looks up the values >>> counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> for key in counts: ... print(key, counts[key]) ... jan 100 chuck 1 fred 42 >>>
  • 39. Retrieving Lists of Keys and Values You can get a list of keys, values, or items (both) from a dictionary >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> print(list(jjj)) ['jan', 'chuck', 'fred'] >>> print(jjj.keys()) ['jan', 'chuck', 'fred'] >>> print(jjj.values()) [100, 1, 42] >>> print(jjj.items()) [('jan', 100), ('chuck', 1), ('fred', 42)] >>> What is a “tuple”? - coming soon...
  • 40. Bonus: Two Iteration Variables! • We loop through the key-value pairs in a dictionary using *two* iteration variables • Each iteration, the first variable is the key and the second variable is the corresponding value for the key jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} for aaa,bbb in jjj.items() : print(aaa, bbb) jan 100 chuck 1 fred 42 [chuck] 1 [fred] 42 aaa bbb [jan] 100
  • 41. name = input('Enter file:') handle = open(name) counts = dict() for line in handle: words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count print(bigword, bigcount) python words.py Enter file: clown.txt the 7 python words.py Enter file: words.txt to 16 Using two nested loops