0% found this document useful (0 votes)
116 views21 pages

Chapter 1 - p5

A dictionary is an unordered collection of key-value pairs that is changeable and indexed. Keys must be unique and are used to access the corresponding value. Values in a dictionary can be accessed by referring to the key inside square brackets or by using the get() method. Items can be added, removed, changed, or looped through using various methods like pop(), popitem(), clear(), update(), etc.

Uploaded by

Emna Boussoffara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views21 pages

Chapter 1 - p5

A dictionary is an unordered collection of key-value pairs that is changeable and indexed. Keys must be unique and are used to access the corresponding value. Values in a dictionary can be accessed by referring to the key inside square brackets or by using the get() method. Items can be added, removed, changed, or looped through using various methods like pop(), popitem(), clear(), update(), etc.

Uploaded by

Emna Boussoffara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

86

PART 4 – D: DICTIONARIES
87

DICTIONARIES
• A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets { }, and they have keys and values.

thisdict={
"brand":"Ford",
"model":"Mustang", Output:
"year":1964 {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
}
print(thisdict)
88

DICTIONARIES
• You can access the items of a dictionary by referring to its key name, inside square
brackets:
thisdict = {
"brand":"Ford",
"model":"Mustang",
Output:
"year":1964
Mustang
}
x = thisdict["model"]
print(x)

• There is also a method called get() that will give you the same result:

x = thisdict.get("model")
89

DICTIONARIES
• You can change the value of a specific item by referring to its key name:

thisdict = {
"brand":"Ford",
"model":"Mustang",
Output:
"year":1964
{'brand': 'Ford', 'model': 'Mustang', 'year': 2019}
}
thisdict["year"]=2019
print(thisdict)
90

DICTIONARIES
• You can loop through a dictionary by using a for loop.
• When looping through a dictionary, the return value are the keys of the dictionary, but
there are methods to return the values as well
thisdict = {
"brand":"Ford",
"model":"Mustang", Output:
"year":1964 brand
} model
year
for x in thisdict:
print(x)

• Print all values in the dictionary, one by one: Output:


Ford
for x in thisdict: Mustang
print(thisdict[x]) 1964
91

DICTIONARIES
• You can also use the values() function to return values of a dictionary:

thisdict = {
"brand":"Ford",
Output:
"model":"Mustang", Ford
"year":1964 Mustang
} 1964
for x in thisdict.values():
print(x)

• Loop through both keys and values, by using the items() function:

Output:
for x,y in thisdict.items(): brand Ford
print(x, y) model Mustang
year 1964
92

DICTIONARIES
• To determine if a specified key is present in a dictionary use the in keyword:

thisdict = {
Output:
"brand":"Ford",
Yes, 'model' is one of the keys in the thisdict
"model":"Mustang",
dictionary
"year":1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

• To determine how many items (key-value pairs) a dictionary has, use the len() method.

Output:
print(len(thisdict))
3
93

DICTIONARIES
• Adding an item to the dictionary is done by using a new index key and
assigning a value to it:

thisdict = {
"brand":"Ford",
"model":"Mustang",
Output:
"year":1964
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
}
thisdict["color"]="red"
print(thisdict)
94

DICTIONARIES
• There are several methods to remove items from a dictionary:
• The pop() method removes the item with the specified key name
• The popitem() method removes the last inserted item
• The del keyword removes the item with the specified key name
• The del keyword can also delete the dictionary completely:
thisdict = { thisdict = { thisdict = {
"brand":"Ford", "brand":"Ford", "brand":"Ford",
"model":"Mustang", "model":"Mustang", "model":"Mustang",
"year":1964 "year":1964 "year":1964}
} } del thisdict["model"]
thisdict.pop("model") thisdict.popitem() print(thisdict)
print(thisdict) print(thisdict del thisdict

Output: Output: Output:


{'brand': 'Ford', 'year': 1964}
{'brand': 'Ford', 'year': 1964} {'brand': 'Ford', 'model': 'Mustang'}
NameError: name 'thisdict' is not defined
95

DICTIONARIES
• The clear() keyword empties the dictionary: It is also possible to use the dict() constructor to
make a dictionary:
thisdict = {
"brand":"Ford", thisdict = dict(brand="Ford",
"model":"Mustang", model="Mustang", year=1964)
"year":1964 # note that keywords are not string
} literals
thisdict.clear() # note the use of equals rather than
print(thisdict) colon for the assignment
print(thisdict)
Output:
Output:
{}
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
96

DICTIONARIES
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing the a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with
the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
97

PART 4- C: LISTS EXAMPLES


98

ADDING SEQUENCES
• Sequences can be concatenated with the addition (plus) operator.

L1=[1,2,3] [4, 5, 6, 1, 2, 3]
L2=[4,5,6] [1, 2, 3, 4, 5, 6, 1, 2, 3]
L2=L2+L1 Traceback (most recent call last):
File
L1+=L2 "C:/Users/alaya124968/PycharmProjects/CS120/Exam
print(L2) ple2 Lists.py", line 8, in <module>
print(L1) L1+"Hello"
L1+"Hello" TypeError: can only concatenate list (not "str") to list

NB: nevertheless we can add two lists with different variable types.
If L3=[“Hello”], L1+L3=[1,2,3,”Hello”]
99

MULTIPLICATION SEQUENCES
• Multiplying a sequence by a number x creates a new sequence where the
original sequence is repeated x times:

L1=[1,2,3]
L=L1*2 [1, 2, 3, 1, 2, 3]
print (L)
100

LENGTH, MINIMUM AND MAXIMUM

numbers = [100, 34, 678]


print(len(numbers)) 3
678
print(max(numbers)) 34
print(min(numbers))
101

DUPLICATE A LIST
L1=[65,92,17] L1=[65,92,17] L1=[65,92,17]
print (L1) print (L1) print (L1)
L2=L1 L2=L1.copy() L2=L1[:]
print(L2) print(L2) print(L2)
L2[1]=55 L2[1]=55 L2[1]=55
print(L2) print(L2) print(L2)
print(L1) print(L1) print(L1)

[65, 92, 17] [65, 92, 17] [65, 92, 17]


[65, 92, 17] [65, 92, 17] [65, 92, 17]
[65, 55, 17] [65, 55, 17] [65, 55, 17]
[65, 55, 17] [65, 92, 17] [65, 92, 17]
Attention: any
modification in L2
would be
automatically in L1
102

INSTRUCTIONS EXAMPLES
L=[1,2,[3,4,[5,6]]] L=[1,2,[3,4,[5,6]]]
print(L[2][2][1]) L[1:2]=[]
print (L)
6
[1, [3, 4, [5, 6]]] Remove the second item

x, y =(2,3,4,5,6)[0:2] 2
print(x) 3
print(y) Traceback (most recent call last):
File
x, y =(2,3,4,5,6)[0:3] "C:/Users/alaya124968/PycharmProjects/CS120/Exam
ple2 Lists.py", line 4, in <module>
Attention: The last instruction select 3 x, y =(2,3,4,5,6)[0:3]
items from the tuple (2,3 and 4) so you ValueError: too many values to unpack (expected 2)
should define 3 variables (x, y and z)
103

INVERSE A LIST
• We can reverse a list using the method reverse

L1=[1, 2, 3] L1=[1, 2, 3]
L1.reverse() OR L1=L1[::-1]
print (L1) print(L1)

[3, 2, 1]
104

ENUMERATE A LIST
• You can have the value of each item in a list with his relevant index using
enumerate

List = ['G', 'o', 'o', 'd'] (0, 'G')


(1, 'o')
for letter in enumerate(List):
(2, 'o')
print(letter) (3, 'd')
105

TRANSFORM A STRING STREAM


INTO A LIST AND VISE VERSA
Split Join

string="Good:to:see:you"
CS_list=["yes","come","in"]
l=string.split(":")
string="*".join(CS_list)
print(l)
print(string)

yes*come*in
['Good', 'to', 'see', 'you']
106

REMOVE DUPLICATE ELEMENTS


INTERSECTION OF TWO LISTS
UNION OF TWO LISTS

a = [0,1,2,0,1,2,3,4,5,6,7,8,9]
b = [5,6,7,8,9,10,11,12,13,14]
#return the list with duplicate elements removed
l=list(set(a))
print(l) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#return the intersection of two lists [8, 9, 5, 6, 7]
l1=list(set(a) & set(b)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(l1)
#return the union of two lists
l2=list(set(a) | set(b))
print(l2)

You might also like