#PYTHON(DAY12)
dictionaries
- dictionaries are ‘key’ & ‘value’ pairs enclosed in ‘{}’
- ‘key’ and ‘value’ are seperated by ‘:’ while ‘key and value’ pairs are seperated by ‘;’
- ‘keys’ are mapped to their ‘values’
- in dictionaries, ‘keys’ are unique, we can not have duplicate keys, we can have duplicate values
- dictionaries are unordered & mutable. ‘keys’ of dictionaries can be used to iterate over values
- ‘{}’ is an empty dictionary
- dict() is class of dictionary
creating a dictionary
x = {}
print(x, type(x))
x = {'key1':1,
'key2':2,
'l1':'eleven',
3:'three',
'key1':100,
'key3':200
}
print(x,type(x))
And the output is:
{} <class 'dict'>
{'key1': 100, 'key2': 2, 'l1': 'eleven', 3: 'three', 'key3': 200} <class 'dict'>
Accessing values using keys
x['key1']
And the output is:
<function print>
x['key2']
And the output is:
[1, 2, 3]
x['key1'](type(['key2']))
And the output is:
<class 'list'>
dictionary methods
print(dir(x))
And the output is:
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
update()
- update method is used to add ‘key’ and ‘value’ pair
- syntax — -> x.update({new_key:value})
x.update({'key6':100})
print(x)
And the output is:
{'key1': <built-in function print>, 'key2': [1, 2, 3], 'key3': (11, 12, 13), 'key4': {4, 5, 6}, 'key5': 'print', 'key6': 100}
x['xyz'] = {'abc':123}
And the output is:
{'key1': <function print>,
'key2': [1, 2, 3],
'key3': (11, 12, 13),
'key4': {4, 5, 6},
'key5': 'print',
'key6': 100,
'xyz': {'abc': 123}}
x['xyz'] = {'def':456}
x
And the output is:
{'key1': <function print>,
'key2': [1, 2, 3],
'key3': (11, 12, 13),
'key4': {4, 5, 6},
'key5': 'print',
'key6': 100,
'xyz': {'def': 456}}
get()
- we use get() to fetch a value
x.get('xyz')
And the output is:
{'def': 456}
x['xyz']
{'def': 456}
keys, values, items
- keys(), values() and items() returns a dict_keys, dict_values, dict_items objects.
- These objects have the keys, values and key & value and tuples of’key and value pairs as elements respectively
- we need to type cast these objects in lists or tuple to see them
a,b,c = x.keys(), x.values(), x.items()
print(a,b,c, sep ='\n')
print()
print(type(a), type(b), type(c))
And the output is:
dict_keys(['key1', 'key2', 'key3', 'key4', 'key5', 'key6', 'xyz'])
dict_values([<built-in function print>, [1, 2, 3], (11, 12, 13), {4, 5, 6}, 'print', 100, {'def': 456}])
dict_items([('key1', <built-in function print>), ('key2', [1, 2, 3]), ('key3', (11, 12, 13)), ('key4', {4, 5, 6}), ('key5', 'print'), ('key6', 100), ('xyz', {'def': 456})])
<class 'dict_keys'> <class 'dict_values'> <class 'dict_items'>
pop()
- pop takes exactly one input/arg i.e the key
- we can capture this popped ‘value’ in a var for further use
bb = x.pop('key6')
print(bb)
100
x
And the output is:
{'key1': <function print>,
'key2': [1, 2, 3],
'key3': (11, 12, 13),
'key4': {4, 5, 6},
'key5': 'print'}
popitem()
- popitem() will pop the last key & value pair if no input is given
- if an key is given as input, it will pop that key and value pair as tuple
bb = x.popitem()
print(bb)
x
('key5', 'print')
{'key1': <function print>,
'key2': [1, 2, 3],
'key3': (11, 12, 13),
'key4': {4, 5,6}}
fromkeys()
- it will create a new dict from the keys of given dict, values by default will be none
- fromkeys() is a class method — -> we will see this in oops
list(x.keys())
['key1', 'key2', 'key3', 'key4']
y = dict.fromkeys(x)
print(y)
{'key1': None, 'key2': None, 'key3': None, 'key4': None}
setdefault()
- The setdefault() method returns the value of the item with the specified key.
- we use to set the default value, if it is not present in dictionary.
- if the key does not exist, then it returns ‘None’
- if we give the default key, value pairs then it display the default value, when the defaultkey is called
x = {1:'milk',
2:'tea powder',
3:'sugar',
4:[1,2,3],
5:{4,5,6}}
print(x)
y = x.setdefault("6")
print(y)
And the output is:
{1: 'milk', 2: 'tea powder', 3: 'sugar', 4: [1, 2, 3], 5: {4, 5, 6}}
None
x.get('hello')
x