0% found this document useful (0 votes)
13 views29 pages

Dictionaries and Sets - ch09

Python study guide

Uploaded by

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

Dictionaries and Sets - ch09

Python study guide

Uploaded by

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

Dictionaries

and Sets
Dictionaries

• While writing a program, in some cases, we want to use keys that we


determine instead of using index numbers to identify elements in structures
that hold multiple elements together.

• We can specify the value of elements in lists and tuples. We may want to
define both the key and the value in some cases.

• For example: If we are writing an English-Turkish dictionary program, the


English word will be the key that allows us to reach the Turkish equivalent
of the word.

• For example: If we are going to store student information, the student


Dictionaries

• Python provides the Dictionary type so that we can define


collections with key-value pairs.

• Dictionaries are editable collections that can be added,


deleted, updated.

• dictionary = {key1:value1,key2:value2, ...}

• Also, an empty dictionary can be defined as: dictionary = {}


Dictionaries

Now let's define a dictionary that will hold English-Turkish word pairs.
lexicon = {"car": "araba", "image": "resim", "coding": "kodlama", "software":
"yazılım"} # In this dictionary, the English of the word is the key, and the Turkish is the
value.

# To access any value in the dictionary, the key of that word (value) must be used.

word = lexicon["software"]
print(word)

yazılım
Accessing Dictionary Elements

If you try to reach the value of a key that is not in the dictionary, a KeyError error occurs.

The get() command allows us to find the value of the key written in parentheses.
However, if the key does not exist, it does not generate a KeyError, it produces a None
result.

lexicon = {"car": "araba", "image": "resim", "coding": "kodlama", "software": "yazılım"}


word = lexicon.get("computer")
print(word)

None
Adding and Editing Elements to
the Dictionary

To add an element in a dictionary the notation is as follows:

dictionary_variable["key"] = "value"

lexicon["pink"] = "pembe"
print(lexicon)

{'car': 'araba', 'image': 'resim', 'coding': 'kodlama', 'software': 'yazılım', 'pink':


'pembe'}
Adding and Editing Elements to
the Dictionary

The process of editing dictionary elements is similar to adding an


element, the key whose value is to be changed is found and the
new value is assigned.

lexicon = {"car": "araba", "image": "resim", "coding": "kodlama",


"software": "yazılım"}
lexicon["image"] = "görüntü"
print(lexicon)

{'car': 'araba', 'image': 'görüntü', 'coding': 'kodlama', 'software': 'yazılım'}


Deleting an Element from the
Dictionary

The del command is used to delete an element from the dictionary.


lexicon = {"car": "araba", "image": "resim", "coding": "kodlama", "software": "yazılım"}
del lexicon["car"] # deletes the car key and its value in the dictionary
print(lexicon)

{'image': 'resim', 'coding': 'kodlama', 'software': 'yazılım’}

The clear() command is used to delete all the elements of the dictionary. After the clear()
command is executed, all the elements in the dictionary are deleted and the empty dictionary {} is
printed to the screen.

lexicon.clear()
print(lexicon)
{}
Listing Dictionary Elements

The elements in the dictionary can be listed with the help of the for loop.

lexicon = {"car": "araba", "image": "resim", "coding": "kodlama", "software":


"yazılım"}
for ky in lexicon:
print("English:", ky, "Turkish:", lexicon[ky])

English: car Turkish: araba


English: image Turkish: resim
English: coding Turkish: kodlama
English: software Turkish: yazılım
items()

The items() command allows us to access both keys and values simultaneously in a dictionary.

dict_items([('car', 'araba'), ('image', 'resim'), ('coding', 'kodlama'), ('software', 'yazılım')])

We can use the items() command with the for loop as follows.
lexicon = {"car": "araba", "image": "resim", "coding": "kodlama", "software": "yazılım"}
for ky, val in lexicon.items():
print("Key:", ky, "Value:", val)

Key: car Value: araba


Key: image Value: resim
Key: coding Value: kodlama
Key: software Value: yazılım
keys() and values()

The keys() and values() commands are used to separately retrieve the keys and values of the
dictionary.

The keys() command accesses the keys of the dictionary.

lexicon = {"car": "araba", "image": "resim", "coding": "kodlama", "software": "yazılım"}


for ky in lexicon.keys():
print(ky)
car
image
coding
software
keys() and values()

The values in the dictionary can be retrieved with the values() command.

lexicon = {"car": "araba", "image": "resim", "coding": "kodlama", "software":


"yazılım"}
for val in lexicon.values():
print(val)

araba
resim
kodlama
yazılım
len()

The len() command is used to find the number of dictionary


elements.
In fact, the number of elements means the number of keys.
Each key value pair counts as a single element.

lexicon = {"car": "araba", "image": "resim", "coding": "kodlama",


"software": "yazılım"}
print(len(lexicon))
Dictionary Elements

The in and not in commands are used to check if a key exists in the dictionary.

The point to be noted here is that only a key can be checked for existence in the
dictionary, while the existence of the value cannot be checked.

lexicon = {"car": "araba", "image": "resim", "coding": "kodlama", "software": "yazılım"}


print("car" in lexicon)
print("hardware" not in lexicon)

True
True
Equality of Dictionaries

The equality of two dictionaries is checked with the == operator, and the
unequal condition is checked with the != operator.

Two dictionaries being equal means that the keys and their corresponding
values, that is, the key-value pairs, are equal.

The order of key-value pairs in the list has no effect on equality.

Even one of the key-value pairs in the dictionary is different makes the two
dictionaries different.
Equality of Dictionaries

stock1 = {"notebook": 9, "eraser": 8}


stock2 = {"notebook": 51, "eraser": 8}
status = stock1 != stock2
print(status)

True
update()

The update() command is used to update keys and values in a dictionary.

The following dictionary named product is updated according to the values in


the new dictionary:

product = {"notebook": 9, "eraser": 8, "tape": 2}


new = {"notebook": 1, "eraser": 2, "tape": 3, "watercolor": 4}
product.update(new)
print(product)

{'notebook': 1, 'eraser': 2, 'tape': 3, 'watercolor': 4}


clear()

The clear() command is used to delete the elements in the dictionary.

The clear() command deletes all the elements in the dictionary, but the
dictionary structure itself is not deleted, the dictionary becomes empty {}

wind = {"north": "north wind", "south": "south wind", "east": "east wind"}
wind.clear()
print(wind)

{}
Dictionary Variables

Dictionaries are reference types, as mentioned earlier on lists.

In other words, the address information where the data is kept in the
memory is held in the dictionary type variables.

Therefore, assigning between two dictionary variables actually causes


the addresses to be synchronized in the background.

In other words, both variables point to the same region in memory.


Dictionary Variables

wind = {"north": "north wind", "south": "south wind",


"east": "east wind"}
predict = wind
print(id(predict))
print(id(wind))

140723374014016
140723374014016
Dictionary Variables

As a natural consequence of this, the change to be made on any of the


predict or wind variables will affect the other.
wind = {"north": "north wind", "south": "south wind", "east": "east wind"}
predict = wind
wind["northwest"] = "nw wind"
print(predict)

We see that the above operation does not copy the contents of a dictionary,
only the values of the variables are synchronized, there is still a single
dictionary dataset in memory.
copy()

The copy() command is used to create a copy of the elements in a


dictionary.

In the following case, the memory addresses of the two variables are not
synchronized, a second copy of the values is created, in this case, changes
to any variable will not affect the other.

wind = {"north": "north wind", "south": "south wind", "east": "east wind"}
predict = wind.copy()
wind["northwest"] = "nw wind"
print(predict)
Sets

• Sets, like lists and tuples, are collections that organize


multiple elements. Unlike tuples, sets are
interchangeable. It can contain different types of
elements. It has all the properties of mathematical
sets. All features such as intersection, union are also
available for sets in Python language. set() is used to
define a set in Python. To create an empty set:

set1 = set()
Sets

• The {} symbol is used to define a set with its


elements. This symbol has also been used to create
dictionaries before, but the difference is that in
dictionaries, elements are defined as key-value pairs,
while in sets they are defined individually:

set2 = {5, 856, "games", False}


print(type(set2))
Sets

• Previously defined lists or tuples can also be converted to a set with


the set() method.

list1 = ["gimli", "aragorn", "legolas"]


names = set(list1)
print(names)
print(list1)

• add() is used to add an element to an existing set.

lotr = set(list1)
lotr.add("9")
print(lotr)
Sets

• To remove an element from an existing set, two separate methods,


remove() and discard(), can be used.

set3 = {4, 8, 9}
set3.remove(8)
print(set3)

• Although the discard() method does the same job as remove(), the
only difference is that if an element that is not in the set is to be
deleted, an error will not occur.

set4 = {4, 8, 9}
Sets

• difference() is used to get the difference between two sets.

set1 = {"a", "r", "d"}


set2 = {"a", "r", "d", "b", "o", "r", "a"}
diff = set2.difference(set1)
print(diff)

• Instead of finding the difference between two sets using the difference() method,
we can also find the difference with '-' operator directly.

• We can find the intersection of set1 and set2 using the intersection() method or the '&'
operator.

intersct = set1 & set2


Sets

• The isdisjoint() method is used to determine the disjoint status of two sets, that is, whether
their intersection is empty or not. This method produces True if the sets are discrete, False
otherwise.

set1 = {4, 9, 6}
set2 = {3, 6, 5}
disjSets = set1.isdisjoint(set2)
print(disjSets)

• The issubset() method is used to check whether a set is a subset of another set.

set1 = {4, 9, 6}
set2 = {6, 4, 7, 9, 5}
print(set1.issubset(set2)) # where set1 and set2 are used is important here

• As opposed to subset querying, issuperset() method is used to find if a set is superset of another set or
Sets

• union() or '|' operator is used to get the union of two


sets.

set1 = {"M", "I", "S"}


set2 = {1, 2, 3}
unionset = set1.union(set2)
print(unionset)

You might also like