Dictionaries
Dictionary
**[also called hash table, map or objects.] **
A dictionary is an unordered key value pair. It can be string, int, booleans, or tuples but mostly stings are considered You cannot have lists or set as a dictionary because they are immutable A key in a dictionary has to be unique
dictionary = {
"key": 'value',
'a': 1,
'b': [1, 2, 3],
'c': 'hello',
'd': True
}
print(dictionary['b'][1])
user = {
'basket': [1, 2, 3],
'greet': 'hello',
'age': 22
}
print(user.get('age')) # returns None this is used to avoid error
print(user.get('age', 22)) # returns 22 [adds default value]
Another way to create dictionary
user2 = dict(name='Marwa')
print(user2)
Another way for looking things in dict
print('basket' in user)
Methods in dict
print('greet' in user.keys()) # returns True if it exists
print('hello' in user.values()) # returns True if it exists
print(user.items()) # shows all items in dictionary
user2 = user.copy() # copies the keys and values
print(user2)
# Updates the item[if does'nt exist adds new item]
print(user.update({'age': 23}))
print(user.pop("age")) # pop off age value
print(user.popitem()) # pops off last item
print(user.clear()) # clears the dict
Dictionary inside a list
my_list = [
{
"key": 'value',
'a': 1,
'b': [1, 2, 3],
'c': 'hello',
'd': True
},
{
"key": 'value',
'a': 2,
'b': [4, 5, 6],
'c': 'hi',
'd': False
}]
print(my_list[0]['b'][1])