Accessing dictionaries in python for beginners

Parameter Details

key = The desired key to lookup
value = The value to set or return

What exactly is a dictionary?

A real-life dictionary holds words and their meanings. As you can imagine, likewise, a Python dictionary holds key-value pairs. Also to be noted that they are Unordered and mutable.

How to create one ?

mydict = {}                #Empty dictionary
mydict = {'key' : 'value'} #Initialized dictionary
person = {'name':'xyz', 'age':23}

Built in Function for creating a dictionary: dict()

myperson = dict() #empty dictionary
myperson = dict(name="xyz", age=23) #here we have given value to dict function

# while using dict function we dont need quotes or colons.

Modifying a dictionary

myperson = dict(name="xyz", age=23) #creating a dict

myperson["email"] = "[email protected]" #adding email as key and its value to dict
Adding list to a dictionary
myperson['new_list'] = [1, 2, 3] #adding new_list as key and [1,2,3] as value
Adding Dictionary to a dictionary
myperson['new_dict'] = {'nested_dict': 1} #new_dict is the key and {'nested_dict': 1} is the value
To delete an item, delete the key from the dictionary
del myperson['email'] #here key is deleted

Iterating Over a Dictionary

Yes, we can iterate over dictionary. Such structures on which we can iterate are called ITERABLE and things which iterates, like 'i' in for loop, that 'i' is called ITERATOR(abstract explanation).

myperson = {'name':'xyz', 'age':23}

for key in myperson:
    print(key, myperson[key],sep=" : ")

# key is iterated , so key is iterator here
The items() method can be used to loop over both the key and value simultaneously
myperson = {'name':'xyz', 'age':23}

for key,values in myperson.items():
    print(key,values)
While the values() method can be used to iterate over only the values
myperson = {'name':'xyz', 'age':23}

for values in myperson.values():
    print(values)

Soon.

24