In this tutorial we are going to learn :

  • Dictionaries In Python
  • Creating Items and Accessing Items
  • Change Dictionary Items
  • Checking Items and Getting Lenght

 

 

 

Dictionaries in Python

 

Dictionary is an unordered, changeable, and indexed collection of items.

  • Dictionaries have key and value.
  • They are written with curly brackets

 

 

 

Creating Items and Accessing Items

 

We use curly brackets to create a dictionary.

  • We also use the dict() method to create a dictionary.
  • To access items in a dictionary, you can use the get() method.

 

Example :

# creating dictionary
first_dictionary = {
    "name": "James"
    "age": 21
}

3 we can also use dict() method to create dictionary 
second_dictionary = dict(name = "John", age = 21)


print(first_dictionary)
print(second_dictionary)

# we use get() method to access items
print(first_dictionary.get("name"))
print(second_dictionary.get("name")) 

 

 

 

Change Dictionary Items

 

We can also change the value of a specific item by referring to its key name.

Example :

# change items

my_dictionary = dict(name = "Adam", age = 21)
print(my_dictionary)

#changing item
my_dictionary["name"] = "John"
print(my_dictionary)

# we can also add a new key
my_dictionary["city"] = "New York"
print(my_dictionary) 

 

 


Checking Items and Getting Lenght


We can use the in keyword to learn if the item exists in dictionary.
To get length of a dictionary , you can use the len() method.

Example :

my_dictionary = dict(name = "James", age = 21)

if "name" in my_dictionary:
    print("exist")
    

# getting lenght
print("Lenght :", len(my_dictionary)) 
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments