DEV Community

Cover image for Accessing dictionaries in python for beginners
Amrut
Amrut

Posted on • Updated on

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}
Enter fullscreen mode Exit fullscreen mode

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. 
Enter fullscreen mode Exit fullscreen mode

Modifying a dictionary

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

myperson["email"] = "xyz@gmail.com" #adding email as key and its value to dict

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

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

Enter fullscreen mode Exit fullscreen mode
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)

Enter fullscreen mode Exit fullscreen mode
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)

Enter fullscreen mode Exit fullscreen mode

Soon.

Top comments (0)