Trending technologies

#AWS #Azure #Blockchain #IOT #machine learning #Virtual Reality #Analytics #Business Intelligence

Tutorials

Blogs

Dictionaries are un ordered sets or un ordered Key Value pair and items.

 

In dictionaries items are accessed via keys and not via their position simply you can say A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value.

Dictionary Example

'''Create and Print Directory

dict = {
  "Name": "Govind",
  "Age": 29
}

print(dict) 

Output:

{"Name": "Govind", "Age": 29}

Accessing Items

By referring to key name you can access the Dictionary Items and also using the get function you can access the Items in Dictionary.


'''Get value of Name Key

print(dict["Name"]) 

Govind

'''Get value of Name Key using get function

data = dict.get("Name")

print(data)

Govind

Change Values

You can change a dictionary by adding a new entry or a key-value pair. You can change any specific item by referencing it is key value.


dict = {
  "Name": "Govind",
  "Age": 29
}

	dict["Name"] = "Hari"

print(dict);

{"Name": "Hari", "Age": 29 )

Delete Dictionary Item

There are several way to remove items from a dictionary:

Remove item using the pop() function.

dict = {
  "Name": "Govind",
  "Age": 29
}

dict.pop("Name")

print(thisdict)
{"Age": 29 }

Remove item using the popitem() function.It will remove the last Item from the dictionary.

dict = {
  "Name": "Govind",
  "Age": 29
}

dict.popitem("Name")

print(dict)

{"Name": "Govind"}

Remove item using the del keyword.

dict = {
  "Name": "Govind",
  "Age": 29
}

del dict["Name"]

print(dict)

{"Age": 29 }

Using del keyword we can delete the complete dictionary.


dict = {
  "Name": "Govind",
  "Age": 29
}

del dict

print(dict)

Traceback (most recent call last):
line 7, in 
print(dict) #this will cause an error because "dict" no longer exists.
NameError: name 'dict' is not defined

Using clear function we can empties the dictionary.

dict = {
  "Name": "Govind",
  "Age": 29
}

dict.clear()

print(dict)

Explained Dictionaries

Python Dictionaries

Dictionary Operations

Spread the Knowledge
error: Content is protected !!