In [ ]:
%autosave 0

Dictionary and Set

Dictionary and Set are also container type data. They can contain any data type, including other continaer type objects. Dictionary and Set are Mutable objects.

Dictionary

dictionary[key] = value will create or update the value in the dictionary.


In [ ]:
x = dict()  # Create empty dictionary
x[0] = 'abc'  # Create
x[0] = 'xyz'  # update
print(x[0])
print(x[1])  # No item... error

In [ ]:
# Dicationary which value is List
# Disctionary is enclosed with brace {}

x = {'a': ['apple', 'anaconda'], 'b': ['beatles', 'beethoven']}
x['b'].append('beegees')
print(x)

In [ ]:
# MCPC rehearsal problem 1

s1 = "Living John Piano"
s2 = "Bath Alice Toothbrush"

who_what_dict = dict()    # Key Where, Value (Who, What)
x = s1.split()
who_what_dict[x[0]] = x[1:]
x = s2.split()
who_what_dict[x[0]] = x[1:]

# What is in Living ?
print(who_what_dict['Living'][1])    # [0]: Who, [1]: What

Set

Set is like a dictionary without value (only key), or List of unique items.

  • Elements of Set can be accessed as a iterable object (can be used in for loop)
  • Elements of Set can not be accessed with Index, (same as Dictionary)
  • String, List, Tuple or other iterable object can be converted to Set

In [ ]:
list_x = [1, 1, 2, 2, 3, 3, 4]
set_x = set(list_x)
print(set_x)

str_x = 'this is a string'
set_x = set(str_x)
print(set_x)

print(set_x[0])   # error

Operators of Set

Product (AND), Union (OR), Exclusive OR (XOR) and Difference are supported as oprators to created evaluated Set. Super Set, Sub Set oprators returns Boolean value.

  • AND: &
  • OR: |
  • XOR: ^
  • Difference: -
  • Superset >
  • Subset <

In [ ]:
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(set_a & set_b)
print(set_a | set_b)
print(set_a ^ set_b)
print(set_a - set_b)

In [ ]:
set_a = {1, 2, 3, 4}
set_b = {3, 4}
set_c = {3, 4}

print (set_a > set_b)   # is set_a a superset of set_b ?
print (set_b > set_a)
print (set_b < set_a)
print (set_b >= set_c)
print (set_b > set_c)