Dictionaries (aka associative array) are ordered collection of data items.
They store multiple items in a single variable.
Dictionary items are key-value pairs that are separated by commas and enclosed within curly brackets { }
.
Example-
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
#Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
info = {
'name': 'Karan',
'age': 19,
'eligible': True
}
Values in a dictionary can be accessed using keys by mentioning keys either in square brackets or by using get method.
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info['name'])
print(info.get('eligible')) # i use this one
#Output:
Karan
True
We can print all of the values in the dictionary using values() method.
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.values())
#Output:
dict_values(['Karan', 19, True])
We can print all the keys in the dictionary using keys() method.
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.keys())
#Output:
dict_keys(['name', 'age', 'eligible'])
We can print all the key-value pairs in the dictionary using items() method.
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.items())
#Output:
dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])
The clear() method Removes all the items from the dictionary.
info = {'name':'Karan', 'age':19, 'eligible':True}
info.clear()
print(info)
# Output:
{}
The pop() method removes the key-value pair whose key is passed as a parameter.
info = {'name':'Karan', 'age':19, 'eligible':True}
info.pop('eligible')
print(info)
#Output:
{'name': 'Karan', 'age': 19}
we can also use the del keyword to remove a dictionary item.
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info['age']
print(info)
del info
print(info)
#Output:
{'name': 'Karan', 'eligible': True, 'DOB': 2003}
NameError: name 'info' is not defined
The popitem() method removes the last key-value pair from the dictionary.
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
info.popitem()
print(info)
#Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
The update() method updates the value of the key provided to it,
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info.update({'age':20})
print(info)
#Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}
Using this method, we can copy a dictionary.
info = {'name': 'Karan', 'age': 19, 'eligible': True}
n_info = info.copy()
print(n_info)
# Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
We can use loop with Dictionaries with .item()
Dict = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
for k,v in Dict.items(): # k,v represents keys, values.
print(f'{k}:',v)
# Output:
name: Karan
age: 19
eligible: True
DOB: 2003