29
loading...
This website collects cookies to deliver better user experience
d = {'game': 'Cricket', 'type': 'One-day', 'over': 50, 'players': 11}
type(d)
# Output: <class 'dict'>
print(d)
# Output
# {'game': 'Cricket', 'type': 'One-day', 'over': 50, 'players': 11}
# dict() function
'''
You can pass the list of tuples, where each tuple will be a key-value pair.
'''
t = dict([('game', 'Cricket'),('type', 'One-day'),('over', 50),('players', 11)])
'''
You can also use mixed type keys to create a dictionary.
'''
c = dict([(1,[1, 2, 3]), ('name', 'Ramesh')])
# Accessing a dictionary value
d = {'game': 'Cricket', 'type': 'One-day', 'over': 50, 'players': 11}
print(d['game'])
# Output: Cricket
print(d['over'])
# Output: 50
# Changing Dictionary Values
c = dict([(1,[1, 2, 3]), ('name', 'Ramesh')])
print(c)
# Output
# {1: [1, 2, 3], 'name': 'Ramesh'}
'''
Suppose if you want to change the 'name' in this dictionary then how would you do that?
'''
c['name'] = 'Kumar'
print(c)
# Output
# {1: [1, 2, 3], 'name': 'Kumar'}
# The 'in' Operator
d = {'game': 'Cricket', 'type': 'One-day', 'over': 50, 'players': 11}
print('game' in d)
# Output: True
print('type' not in d)
# Output: False
# Define an empty Set
b = {}
t = set()
type(b)
# Output: <class 'dict'>
type(t)
# Output: <class 'set'>
set1 = set('Books')
set2 = set([1,1,2,3,4,4,5,6])
set3 = set(('one', 'two', 'one', 'three', 'four', 'two'))
print('set1:', set1)
print('set2:', set2)
print('set3:', set3)
# Output
# set1: {'B', 'k', 's', 'o'}
# set2: {1, 2, 3, 4, 5, 6}
# set3: {'four', 'two', 'one', 'three'}
# Adding the value
s = {4, 'Text', True, False, 3.14}
s.add('Hello')
print(s)
# Output
# {False, True, 3.14, 4, 'Text', 'Hello'}
# Removing the value
s.discard(True)
print(s)
# Output
# {False, 3.14, 4, 'Text', 'Hello'}
# Union of sets
x = {1, 4, 6, 3, 9}
y = {'a', 'b', 'c', 4}
xy = x | y
print('xy', xy)
# Output
# {'c', 1, 3, 4, 6, 9, 'a', 'b'}
# Using union() function.
x.union(y)
# Output
# {'c', 1, 3, 4, 6, 9, 'a', 'b'}
y.union(x)
# Output
# {'c', 1, 3, 4, 6, 9, 'a', 'b'}
# Intersection
x = {1, 4, 6, 3, 'c'}
y = {'a', 'b', 'c', 4}
# Using & operator
x_and_y = x & y
print(x_and_y)
# Output
# {'c', 4}
# Using intersection() method.
x.intersection(y)
# Output: {'c', 4}
y.intersection(x)
# Output: {'c', 4}
# Difference
x = {1, 4, 6, 3, 'c'}
y = {'a', 'b', 'c', 4}
# Using ‘-’ operator
x_diff_y = x - y
print(x_diff_y)
# Output
#{1, 3, 6}
y_diff_x = y - x
print(y_diff_x)
# Output
# {'a', 'b'}
# Using difference() method.
x.difference(y)
# Output:{1, 3, 6}
y.difference(x)
# Output: {'a', 'b'}
# Symmetric Difference
x = {1, 4, 6, 3, 'c'}
y = {'a', 'b', 'c', 4}
# Using '^' operator
x_sdiff_y = x ^ y
print(x_sdiff_y)
# Output
# {1, 3, 6, 'a', 'b'}
# Using symmetric_difference() method.
x.symmetric_difference(y)
# Output:{1, 3, 6, 'a', 'b'}
y.symmetric_difference(x)
# Output: {1, 3, 6, 'a', 'b'}
# The 'in' Operator
y = {'a', 'b', 'c', 4}
print('c' in y)
# Output: True
print(5 not in y)
# Output: True