Python Part 2
Python Part 2
Python Part 2
When we create a tuple, we normally assign values to it. This is called "packing" a
tuple:
ruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
apple
banana
cherry
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the
position of where it was found
Python Sets
myset = {"apple", "banana", "cherry"}
Set
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set
has been created.
Once a set is created, you cannot change its items, but you can remove items and
add new items
Note: The values True and 1 are considered the same value in sets, and are treated
as duplicates:
Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Add Sets
To add items from another set into the current set, use the update() method.
Exampe
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Add Any Iterable
The object in the update() method does not have to be a set, it can be any iterable
object (tuples, lists, dictionaries etc.).
Example
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
{'banana', 'cherry', 'apple', 'orange', 'kiwi'}
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:
thisset.remove("banana")
print(thisset)
Note: If the item to remove does not exist, remove() will raise an error.
thisset.discard("banana")
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop() method to remove an item, but this method will remove
a random item, so you cannot be sure what item that gets removed
The clear() method empties the set:
thisset.clear()
print(thisset)
z = x.intersection(y)
print(z)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
Return a set that contains all items from both sets, except items that are
present in both:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
Difference
Return a set that contains the items that only exist in set x, and not in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
{'banana', 'cherry'}
Dictionary
Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ford
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"date": 20
}
print(len(thisdict))
4
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 20
}
print(len(thisdict))
3
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Mustang
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = thisdict.get("model")
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
x = thisdict.keys()
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
Get Values
The values() method will return a list of all the values in the dictionary.
Example
Get a list of the values:
x = thisdict.values()
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs
x = thisdict.items()
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Update Dictionary
The update() method will update the dictionary with the items from the given
argument.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning
a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
for x in thisdict:
print(x)
brand
model
year
for x in thisdict:
print(thisdict[x])
Ford
Mustang
1964
for x in thisdict.values():
print(x)
for x in thisdict.keys():
print(x)
for x, y in thisdict.items():
print(x, y)
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
or
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily["child2"]["name"])
Tobias
Sort the value in Dictionary
key_value = {}
# Initializing value
key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print("key_value", key_value)
for i in sorted(key_value.values()):
print(i,end=" ")
OUTPUT
key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}
2 12 18 24 56 323
By default Python‘s print() function ends with a newline.
Python’s print() function comes with a parameter called ‘end‘. By default, the
value of this parameter is ‘\n’, i.e. the new line character.
Here, we can end a print statement with any character/string using this
parameter.