Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.

Example

Create and print a dictionary:

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

 

Output

Accessing Items

You can access the items of a dictionary by referring to its key name:

Example

Get the value of the “model” key:

x = thisdict["model"]

 

Output

Change Values

You can change the value of a specific item by referring to its key name:

Example

Change the “year” to 2018:

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018

 

Output

Loop Through a Dictionary

You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Example

Print all key names in the dictionary, one by one:

for x in thisdict:
  print(x)

 

Output

Example

Print all values in the dictionary, one by one:

for x in thisdict:
  print(thisdict[x])

 

Output

Leave a Reply

Your email address will not be published. Required fields are marked *