Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

(L4)Programming with Python (Intermediate Level)

This document provides an overview of dictionaries in Python, highlighting their structure as key-value pairs and their advantages over lists. It includes examples of creating, modifying, and accessing dictionaries, as well as methods for counting occurrences and iterating through items. Additionally, it offers exercises for practical application and comparisons with other data structures.

Uploaded by

hobohin914
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

(L4)Programming with Python (Intermediate Level)

This document provides an overview of dictionaries in Python, highlighting their structure as key-value pairs and their advantages over lists. It includes examples of creating, modifying, and accessing dictionaries, as well as methods for counting occurrences and iterating through items. Additionally, it offers exercises for practical application and comparisons with other data structures.

Uploaded by

hobohin914
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Programming with Python

(Intermediate Level)
Lesson-4 Dictionary

Coding ညေကျာင်း by Code Champs Coding School


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
A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a
dictionary, the indices can be (almost) any type.
A dictionary is as a mapping between a set of indices (which are called keys) and a set of
values.
Each key maps to a value. The association of a key and a value is called a key-value pair or
sometimes an item.
Dictionaries
Dictionaries are Python’s most powerful data collection

Dictionaries allow us to do fast database-like operations in Python

Dictionaries have different names in different languages

- Associative Arrays - Perl / PHP

- Properties or Map or HashMap - Java

- Property Bag - C# / .Net


How to build a dictionary?
Because dict is the name of a built-in function, you should avoid using it as a variable
name.
Dictionary literals use curly braces and have a list of key : value pairs.
The curly brackets, {}, represent an empty dictionary.
As an example, we’ll build a dictionary that maps from English to Spanish words, so
the keys and the values are all strings.
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(eng2sp['two']) Run program and
print(eng2sp['four']) what are you seeing?
Example: To add items to the dictionary, you can use square brackets:

The function dict creates a


purse = dict() new dictionary with no items.

purse['money'] = 12

purse['candy'] = 3
{'money': 12, 'tissues': 75, 'candy': 3}
purse['tissues'] = 75

print(purse)

purse['candy'] = purse['candy'] + 2

print(purse)
{'money': 12, 'tissues': 75, 'candy': 5}
To see whether something appears as a value in a dictionary,
We can use the method values, which returns the values as a type that can be
converted to a list.

vals = list(eng2sp.values())
How about keys()?
print(vals)
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
y = car.values()
print(y)
Comparing Lists and Dictionaries
>>> lst = list()
>>> lst.append(21)
Dictionaries are like lists except >>> lst.append(183)
that they use keys instead of >>> print(lst)
numbers to look up values. >>> lst[0] = 23
>>> print(lst)
Lists index their entries based on
the position in the list.
>>> ddd = dict()
Dictionaries are like bags - no >>> ddd['age'] = 21
order. >>> ddd['course'] = 182
>>> print(ddd)
So we index the things we put in
>>> ddd['age'] = 23
the dictionary with a “lookup tag” >>> print(ddd)
Comparing Lists and Dictionaries
Do it yourself

1. Person:

Use a dictionary to store information about a person you know. Store their first
name, last name, age, and the city in which they live. You should have keys such
as first_name, last_name, age, and city. Print each piece of information stored in
your dictionary.

2. Favorite Numbers:

Use a dictionary to store people’s favorite numbers. Think of five names, and use
them as keys in your dictionary. Think of a favorite number for each person, and
store each as a value in your dictionary. Print each person’s name and their
favorite number.
Many Counters with a Dictionary
One common use of dictionaries is counting how often we “see” something

>>> ccc = dict() Dictionary Tracebacks


>>> ccc['csev'] = 1
>>> ccc['cwen'] = 1 It is an error to reference a key which
>>> print(ccc) is not in the dictionary
We can use the in operator to see if a
{'csev': 1, 'cwen': 1} key is in the dictionary

>>> ccc['cwen'] = ccc['cwen'] + 1


if 'cewn' in ccc:
>>> print(ccc)
ccc['cwen'] = ccc['cwen'] + 1
{'csev': 1, 'cwen': 2}
List to Dictionary
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)
The get Method for Dictionaries
The pattern of checking to see if a key
is already in a dictionary and
counts = dict()
assuming a default value if the key is names = ['csev', 'cwen', 'csev', 'zqian',
not there is so common that there is a 'cwen']
for name in names :
method called get() that does this for counts[name] = counts.get(name, 0) + 1
us. print(counts)

Default value if key does not exist Default


(and no Traceback).

We can use get() and provide a default


{'csev': 2, 'zqian': 1, 'cwen': 2}
value of zero when the key is not yet in
the dictionary - and then just add one.
The general pattern to count the words in a line of text is
to split the line into words, then loop through the words
Counting Pattern and use a dictionary to track the count of each word
independently.
counts = dict()
print('Enter a line of text:')
line = input('')
words = line.split() Input the following line and check the result!
print('Words:', words)
the clown ran after the car and the car ran into the tent and
print('Counting...') the tent fell down on the clown and the car

for word in words:


counts[word] = counts.get(word,0) + 1
print('Counts', counts)
Can you tell me which word is the most common use?
Dictionary as a set of counters
Suppose you are given a string and you want to count how many times each letter appears. There are several ways
you could do it:

1. You could create 26 variables, one for each letter of the alphabet. Then you could traverse the string and, for
each character, increment the corresponding counter, probably using a chained conditional.
2. You could create a list with 26 elements. Then you could convert each character to a number (using the built-in
function ord), use the number as an index into the list, and increment the appropriate counter.
3. You could create a dictionary with characters as keys and counters as the corresponding values. The first time
you see a character, you would add an item to the dictionary. After that you would increment the value of an
existing item.

Each of these options performs the same computation, but each of them implements that computation in a different
way.

An implementation is a way of performing a computation; some implementations are better than others. For example,
an advantage of the dictionary implementation is that we don’t have to know ahead of time which letters appear in the
string and we only have to make room for the letters that do appear.
Exercise
1. Write a program to read through a mail log, build a histogram using a
dictionary to count how many messages have come from each email address,
and print the dictionary.
2. This program records the domain name (instead of the address) where the
message was sent from instead of who the mail came from (i.e., the whole
email address). At the end of the program, print out the contents of your
dictionary.
3. How to delete item from dictionary and how to handle the exception that
raises a KeyError if key is not in the map?
Hints→ https://docs.python.org/3.10/library/stdtypes.html#mapping-types-dict
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])

You can get a list of keys, values, or items (both) from a dictionary
print(list(jjj.items()))

A items() method is used with a dictionary to get the list with all dictionary keys
with values.
This method actually returns a view object that contains the key-value pairs of the
dictionary, as tuples in a list.
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)

You might also like