0% found this document useful (0 votes)
4 views17 pages

Python Lists Sets Dictionary

Uploaded by

G
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)
4 views17 pages

Python Lists Sets Dictionary

Uploaded by

G
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/ 17

Sort the list alphabetically:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)

Sort the list numerically:

thislist = [100, 50, 65, 82, 23]


thislist.sort()
print(thislist)

Sort the list descending:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort(reverse = True)
print(thislist)

Sort the list descending:

thislist = [100, 50, 65, 82, 23]


thislist.sort(reverse = True)
print(thislist)

Sort the list based on how close the number is to 50:

def myfunc(n):
return abs(n - 50)

thislist = [100, 50, 65, 82, 23]


thislist.sort(key = myfunc)
print(thislist)

Case sensitive sort: (brings unexpected result)

thislist = ["banana", "Orange", "Kiwi", "cherry"]


thislist.sort()
print(thislist)

Perform a case-insensitive sort of the list:

thislist = ["banana", "Orange", "Kiwi", "cherry"]


thislist.sort(key = str.lower)
print(thislist)

Reverse the order of the list items:

thislist = ["banana", "Orange", "Kiwi", "cherry"]


thislist.reverse()
print(thislist)
Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]


mylist = thislist.copy()
print(mylist)

Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)

Make a copy of a list with the : operator: (slice operator)

thislist = ["apple", "banana", "cherry"]


mylist = thislist[:]
print(mylist)

Join two list:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Append list2 into list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1)

Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
Sets

- Sets are used to store multiple items in a single variable.


- A set is a collection which is unordered, unchangeable*, and unindexed.
- Sets are written with curly brackets.

* Note: Set items are unchangeable, but you can remove items and add new items.

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)

False and 0 is considered the same value:

thisset = {"apple", "banana", "cherry", False, True, 0}

print(thisset)

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

What is the data type of a set?

myset = {"apple", "banana", "cherry"}


print(type(myset))

Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets


print(thisset)
Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Check if "banana" is NOT present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" not in thisset)

Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Add elements from tropical into thisset:

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

Add elements of a list to at set:

thisset = {"apple", "banana", "cherry"}


mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)
Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

Remove "banana" by using the discard() method:

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

Remove a random item by using the pop() method:

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

Loop through the set, and print the values:


thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Join Sets

There are several ways to join two or more sets in Python.

- The union() and update() methods joins all items from both sets.
- The intersection() method keeps ONLY the duplicates.
- The difference() method keeps the items from the first set that are not in the other set(s).
- The symmetric_difference() method keeps all items EXCEPT the duplicates.

Join set1 and set2 into a new set:

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

Use | to join two sets: (pipe symbol)

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}

set3 = set1 | set2


print(set3)

Join multiple sets with the union() method:

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}

myset = set1.union(set2, set3, set4)


print(myset)

Use | to join two sets:

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}

myset = set1 | set2 | set3 |set4


print(myset)

Join a set with a tuple:

x = {"a", "b", "c"}


y = (1, 2, 3)

z = x.union(y)
print(z)

The update() method inserts the items in set2 into set1:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

set1.update(set2)
print(set1)

Keep ONLY the duplicates

- The intersection() method will return a new set, that only contains the items that are
present in both sets.

Example

Join set1 and set2, but keep only the duplicates:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1.intersection(set2)
print(set3)

Use & to join two sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1 & set2


print(set3)
Keep the items that exist in both set1, and set2:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set1.intersection_update(set2)

print(set1)

Join sets that contains the values True, False, 1, and 0, and see what is considered as
duplicates:

set1 = {"apple", 1, "banana", 0, "cherry"}


set2 = {False, "google", 1, "apple", 2, True}

set3 = set1.intersection(set2)

print(set3)

Keep all items from set1 that are not in set2:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1.difference(set2)

print(set3)

Use - to join two sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1 - set2


print(set3)

Use the difference_update() method to keep the items that are not present in both sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set1.difference_update(set2)
print(set1)

Keep the items that are not present in both sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1.symmetric_difference(set2)

print(set3)

Use ^ to join two sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1 ^ set2


print(set3)

Use the symmetric_difference_update() method to keep the items that are not present in both
sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set1.symmetric_difference_update(set2)

print(set1)

Dictionary

- Dictionaries are used to store data values in key:value pairs.


- A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
- Dictionaries are written with curly brackets, and have keys and values:

Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Duplicate values will overwrite existing values:


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

Print the number of items in the dictionary:

print(len(thisdict))

Print the data type of a dictionary:

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

Using the dict() method to make a dictionary:

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)

Get the value of the "model" key:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

Get the value of the "model" key:

x = thisdict.get("model")
The keys() method will return a list of all the keys in the dictionary.

Example

Get a list of the keys:

x = thisdict.keys()

The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will
be reflected in the keys list.

Example

Add a new item to the original dictionary, and see that the keys list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

Get a list of the values:

x = thisdict.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()

The list of the values is a view of the dictionary, meaning that any changes done to the dictionary
will be reflected in the values list.

Example

Make a change in the original dictionary, and see that the values list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

Add a new item to the original dictionary, and see that the values list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

Get a list of the key:value pairs

x = thisdict.items()

The returned list is a view of the items of the dictionary, meaning that any changes done to the
dictionary will be reflected in the items list.

Example

Make a change in the original dictionary, and see that the items list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x) #before the change

car["year"] = 2020
print(x) #after the change

Add a new item to the original dictionary, and see that the items list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

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")

Change the "year" to 2018:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Update the "year" of the car by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding an item to the dictionary is done by using a new index key and assigning a value to it:

ExampleGet your own Python Server

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

Add a color item to the dictionary by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})

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)
The del keyword removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

The clear() method empties the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Print all key names in the dictionary, one by one:

for x in thisdict:
print(x)

Print all values in the dictionary, one by one:

for x in thisdict:
print(thisdict[x])

You can also use the values() method to return values of a dictionary:

for x in thisdict.values():
print(x)

You can use the keys() method to return the keys of a dictionary:

for x in thisdict.keys():
print(x)

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

for x, y in thisdict.items():
print(x, y)

Make a copy of a dictionary with the copy() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

Make a copy of a dictionary with the dict() function:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries

A dictionary can contain dictionaries, this is called nested dictionaries.

Create a dictionary that contain three dictionaries:

myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

Create three dictionaries, then create one dictionary that will contain the other three
dictionaries:

child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

Access Items in Nested Dictionaries

To access items from a nested dictionary, you use the name of the dictionaries, starting with the
outer dictionary:

Example

Print the name of child 2:

print(myfamily["child2"]["name"])

Loop through the keys and values of all nested dictionaries:

for x, obj in myfamily.items():


print(x)

for y in obj:
print(y + ':', obj[y])

You might also like