More Data Types: Dictionaries and Sets

Dictionaries

Dictionaries

What is a Dictionary?

An unordered collection of objects (values)
Each value is associated with a unique key.
A dictionary can be regarded as a collection of key:value pairs
Dictionaries in Python are similar to associative arrays, hashes (hash tables) in other programming languages (PHP, Perl, Ruby)

Dictionary Structure

Syntax


			dictionary = {
			'key1': value 1,
			'key2': value 2,
			'keyN': value N
			}
		
There is no order in dictionary! We can not say if 'key1' pair will be before 'key2' pair
Keys must be immutable data type. Usually they are strings.

Retrieve item from dictionary

Dictionary values can be retrieved from the collection using their respective keys.


				item = dictionary_name[key]
		

			prices = {
			  "apples": 2.50,
			  "oranges": 2.43,
			  "bananas": 3.50
			}

			apples_price = prices['apples']
			print("{:.2f}".format(apples_price))
			# 2.50

			oranges_price = prices['oranges']
			print("{:.2f}".format(oranges_price))
			# 2.43
		

Change item in a dictionary


				dictionary_name[key] = new_value
		

			### change apples prices:
			prices['apples'] = 2.20
			print(prices)
			# {'apples': 2.2, 'oranges': 2.43, 'bananas': 3.5}
		

Add item in a dictionary


			dictionary_name[new_key] = new_value
		

			prices = {
			    "apples": 2.50,
			    "oranges": 2.43,
			    "bananas": 3.50
			}

			### add new key:value pair:
			prices['plums'] = 4.30
			print(prices)
			# {'apples': 2.5, 'oranges': 2.43, 'bananas': 3.5, 'plums': 4.3}
		

Delete item from dictionary: del - operator


			del dictionary[key]
		
Deletes the key:value pair whit the given key

			prices = {
				"apples": 2.50,
				"oranges": 2.43,
				"bananas": 3.50
			}

			### just delete 'oranges' key:value pair:
			del prices['oranges']
			print(prices)
			# {'apples': 2.5, 'bananas': 3.5}
		

Delete item from dictionary: pop()


			pop(key[, default])
		
If key is in the dictionary, remove it and return its value, else return default.
If no key or default values are given a KeyError is raised.

Delete item from dictionary: pop() - example


			prices = {
			  "apples": 2.50,
			  "oranges": 2.43,
			  "bananas": 3.50
			}

			### remove 'apples' key:value pair from the dictinary, and return its value
			apples_price = prices.pop('apples')
			print(apples_price, prices)
			# 2.5 {'oranges': 2.43, 'bananas': 3.5}

			apples_price = prices.pop('apples', 5.00)
			print(apples_price)
			# 5.0
		

Get all dictionary keys: keys()


			prices = {
			    "apples": 2.50,
			    "oranges": 2.43,
			    "bananas": 3.50
			}

			fruits = prices.keys()
			print(fruits)
			# dict_keys(['apples', 'oranges', 'bananas'])
		

Get all dictionary values: values()


			prices = {
			    "apples": 2.50,
			    "oranges": 2.43,
			    "bananas": 3.50
			}

			price_list = prices.values()
			print(price_list)
			# dict_values([2.5, 2.43, 3.5])
		

Iterate over dictionary keys:


			for key in dict_name:
				# do something with a key
				# do something with a value: dict_name[key]
		

			prices = {
			    "apples": 2.50,
			    "oranges": 2.43,
			    "bananas": 3.50
			}

			for key in prices:
			    print("{} - {}".format(key, prices[key]))
			# apples - 2.5
			# oranges - 2.43
			# bananas - 3.5
		

Iterate over keys and values


			for key, value in dict_name.items():
				# do something with a key
				# do something with a value
		

			prices = {
			    "apples": 2.50,
			    "oranges": 2.43,
			    "bananas": 3.50
			}

			for fruit, price in prices.items():
			    print("{} - {}".format(fruit, price))
			# apples - 2.5
			# oranges - 2.43
			# bananas - 3.5
		

More on dictionaries

dict class in docs.python.org

Sets

Sets

What is a Set?

An unordered collection of unique and immutable objects.
Set data type in Python is an implementation of the sets as they are defined in mathematics.

Sets vs Dictionaries

Similarities:
Both are unordered collection of objects (values).
Both are mutable (add/remove/modify elements)
Both use curly braces for their literals.
Differences:
A Set can not contain duplicate items! Dictionaries can.
A dictionary is a collection of key:value pairs.
Set is just a values collection

Syntax


			set = {value1, value2, valueN}
		
There is no order in a set! We can not say if 'value1' pair will be before 'value2'.
No duplicate items are allowed. If we define a set with duplicate items, only one of them will be present in the set. Others are ignored.

Simple set - example


			int_numbers = {1, 2, 3, 4, 5}
			print(int_numbers)
			print(type(int_numbers))

			# {1, 2, 3, 4, 5}
			# <class 'set'>
		

Ignoring duplicate items - example 1


			int_dup_numbers = {1, 2, 3, 1, 2, 4, 3, 5, 1, 2, 3}
			print(int_dup_numbers)

			# {1, 2, 3, 4, 5, 6}
		

Ignoring duplicate items - example 2


			int_numbers = {1, 2, 3, 4, 5}
			int_dup_numbers = {1, 2, 3, 1, 2, 4, 3, 5, 1, 2, 3}

			print(int_numbers == int_dup_numbers)

			# True
		

Basic sets operations

Basic sets operations

Sets Union

Returns new set, which elements are in either sets.

Sets Union - example

Pipe operator | or method union can be used


			set1 = {1, 2, 3, 4}
			set2 = {5, 4}

			union1 = set1 | set2
			union2 = set1.union(set2)
			print(union1)
			print(union2)

			# {1, 2, 3, 4, 5}
			# {1, 2, 3, 4, 5}
		

Sets Intersection

Returns new set, which elements belong to both sets.

Sets Intersection - example

Ampersand operator & or method intersection can be used


			set1 = {1, 2, 3, 4}
			set2 = {5, 4}

			intersec1 = set1 & set2
			intersec2 = set1.intersection(set2)
			print(intersec1)
			print(intersec2)

			# {4}
			# {4}
		

Sets Difference

C = A - B, where C is a new set, which elements are the elements of A, which are not present in B

Sets Difference - example

Operator - or method difference can be used


			set1 = {1, 2, 3, 4, 5}
			set2 = {5, 4}

			dif1 = set1.difference(set2)
			dif2 = set1 - set2
			print(dif1)
			print(dif2)

			# {1, 2, 3}
			# {1, 2, 3}
		

Sets Symmetric Difference

C = A △ B, where C is a new set, which elements are either in sets A or B but not in both.

Sets Symmetric Difference - example

Pipe operator | or method union can be used


			set1 = {1, 2, 3, 4}
			set2 = {5, 4}

			sym_dif = set1.symmetric_difference(set2)
			print(sym_dif)

			# {1, 2, 3, 5}
		

More on sets

set class in docs.python.org

Exercises

Task1

Represent the information given in next table in appropriate data structure, named student_scores.
From student_scores data, create a new data structure named best_student_scores, storing the information (name and score) only for students with scores greater than 4.00
Print out the names of the students from best_students

			Ivan
			Maria
			Georgy
		

These slides are based on

customised version of

Hakimel's reveal.js

framework