top of page

Dictionaries in Python

Updated: Apr 19, 2023



Python supports dictionaries.

They are key-value pairs.


Keys are unique. Values can be any data type.


a = {
    "cycle": "ABC",
    "year": 1999
}

print(a)


In order to add a new key, we can write the key name within double quotes and assign the value as shown below.



#add
a["country"] = "India"
print(a)


We can use the get method to get the value of a key.



print(a.get("country"))

keys() and values() methods can be used to get all the keys and values present in the dictionary.



print(a.keys())
print(a.values())



We can iterate over all the items using the items() method.



for x, y in a.items():
    print(x,y)


In order to check whether a key is present, we can directly use if statement as shown below.



if "country" in a:
    print(True)

The update method can be used to update the value of a key.



a.update({"year": 2000})
print(a)


popitem() removes the last item in the dictionary.



a.popitem()
print(a)


clear() removes all elements in the dictionary.


a.clear()
print(a)

The link to the Github repository is here .

Subscribe to get all the updates

© 2025 Metric Coders. All Rights Reserved

bottom of page