24
Accessing dictionaries in python for beginners
Parameter Details
key = The desired key to lookup
value = The value to set or return
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.
mydict = {} #Empty dictionary
mydict = {'key' : 'value'} #Initialized dictionary
person = {'name':'xyz', 'age':23}
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.
myperson = dict(name="xyz", age=23) #creating a dict
myperson["email"] = "[email protected]" #adding email as key and its value to dict
myperson['new_list'] = [1, 2, 3] #adding new_list as key and [1,2,3] as value
myperson['new_dict'] = {'nested_dict': 1} #new_dict is the key and {'nested_dict': 1} is the value
del myperson['email'] #here key is deleted
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
myperson = {'name':'xyz', 'age':23}
for key,values in myperson.items():
print(key,values)
myperson = {'name':'xyz', 'age':23}
for values in myperson.values():
print(values)
24