Automation Crunch ๐Ÿ˜Ž
March 7, 2022

Python Dictionary

Posted on March 7, 2022  •  3 minutes  • 497 words

A dictionary is an unsorted, changeable, and indexed collection. Curly brackets are used to write dictionaries in Python, and they have keys and values.


# 1.Create and print a dictionary
>>> dt = {
        "brand": "Nissan",
        "model": "Altima",
        "year": 2022
        }
>>> print(dt)
{'brand': 'Nissan', 'model': 'Altima', 'year': 2022} # Output

# 2.Get the value of the "model" key:
>>> dt = {
        "brand": "Nissan",
        "model": "Altima",
        "year": 2022
        }
>>> x = dt["model"]
>>> print(x)
Altima # Output

# 3.Change the "year" to 2018:
>>> dt = {
        "brand": "Nissan",
        "model": "Altima",
        "year": 2022
        }
>>> dt["year"] = 2018
>>> print(dt)
{'brand': 'Nissan', 'model': 'Altima', 'year': 2018} # Output: date changed

# 4.Print all key names in the dictionary, one by one:
>>> dt = {
        "brand": "Nissan",
        "model": "Altima",
        "year": 2018
        }
>>> for x in dt:
...     print(x)
...
        # Below is Output
brand
model
year

# 5.You can also use the values() function to return values of a dictionary:
>>> dt = {
        "brand": "Nissan",
        "model": "Altima",
        "year": 2018
        }
>>> for x in dt.values():
...     print(x)
...
Nissan
Altima
2018

# 6.Loop through both keys and values, by using the items() function:
>>> dt = {
        "brand": "Nissan",
        "model": "Altima",
        "year": 2018
        }
>>> for x, y in dt.items():
...     print(x, y)
...
        # Below is Output
brand Nissan
model Altima
year 2018

# 7.Adding Items : Adding an item to the dictionary is done by using a new index key and assigning a value to it:
>>> dt = {
        "brand": "Nissan",
        "model": "Altima",
        "year": 2018
        }
>>> dt["color"] = "red"
>>> print(dt)
{'brand': 'Nissan', 'model': 'Altima', 'year': 2018, 'color': 'red'} # Output

# 8.The pop() method removes the item with the specified key name:
>>> dt = {
        "brand": "Nissan",
        "model": "Altima",
        "year": 2018,
        "color": "red"
        }
>>> dt.pop("model")
>>> print(dt)
{'brand': 'Nissan', 'year': 2018, 'color': 'red'}

# 9.The del keyword removes the item with the specified key name:
>>> dt = {
        "brand": "Nissan",
        "year": 2018,
        "color": "red"
        }
>>> del dt["color"]
>>> print(dt)
{'brand': 'Nissan', 'year': 2018} # Output

# 10.The clear() method empties the dictionary:
>>> dt = {
        "brand": "Nissan",
        "year": 2018
        }
>>> dt.clear()
>>> print(dt)
{} # Output
Follow me

You can find me on