Python Dictionaries

Python Dictionaries

A beginner's guide to understanding the usage of Python dictionaries.

A Python dictionary stores items in the form of a key-value pair. The values stored in a dictionary can be changed, but the dictionary itself cannot be duplicated.

Python dictionaries are pretty easy to understand, and any confusion about them will be cleared up in this article.

Creating a Dictionary

Dictionaries store items as keys that have associated values, which come together to form key-value pairs. The key-value pairs are enclosed in curly braces ({}) and separated from other similar items by commas (,). The keys of the dictionary must be unique and immutable, but this does not apply to the values. For keys to be immutable, they have to be in the form of strings, numbers, or tuples. Look at this dictionary below, which stores the names of popular footballers as keys and their countries of origin as values:

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}

Accessing a Value in the Dictionary

To get a particular value in a dictionary, you will have to access the key that is associated with the value. You can do this by using the get() method. If you provide a key that doesn’t exist, it gives you a value of none.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}
print(origins.get("messi"))

Output:

However, the most popular method of getting values from a dictionary is to use square brackets ([]). You simply have to put the key inside the square brackets ([]), and it returns the value.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}

print(origins["neymar"])

Output:

Updating Values in a Dictionary

Dictionaries are mutable just like lists and sets, which means that the stored values can be changed. You can change values associated with a key using the update() method. Once you update the values and run the code, it will give you a dictionary with the updated value.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}
origins.update({"mbappe": "algeria"})
print(origins)

Output:

Removing/deleting Items from a Dictionary

There are various methods of removing /deleting items from a dictionary, which you will need to know. These methods include:

  1. pop() method

    This will remove the specified key and its value from the dictionary.

     origins= {
         "ronaldo": "portugal",
         "messi": "argentina",
         "neymar": "brazil",
         "mbappe": "france"
     }
     origins.pop({"mbappe": "algeria"})
     print(origins)
    

    Output:

  2. popitem() method

    This removes the item that was last added to the dictionary. It doesn’t require any key.

     origins= {
         "ronaldo": "portugal",
         "messi": "argentina",
         "neymar": "brazil",
         "mbappe": "france"
     }
     origins.popitem()
     print(origins)
    

    Output:

  3. clear() method

    It removes every item in a dictionary and simply returns an empty dictionary.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}
origins.clear()
print(origins)

Output:

Getting All the Keys in a Dictionary

You can use the keys() method to access all the keys in a dictionary at once. Once you run the code, it will return an object that looks like a list containing all the keys.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}

print(origins.keys())

Output:

You can use a for loop to access the keys individually, just like in the code below:

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}
for key in origins.keys():
    print(key + " is good")

Output:

Using the values() method in a Dictionary

The values() method returns all the values in a dictionary at once. It returns an object that resembles a list containing all the values.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}

print(origins.values())

Output:

You can also use a for loop to get the values. Check out this code snippet below:

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}
for key in origins.values():
    print(value + " is a country")

Output:

Getting Both the Keys and Values Simultaneously

It is possible to get both keys and values at the same time in the dictionary. You will have to use the items() method to carry out this operation. It will return an object that is like a 2D list of tuples and contains both the keys and values.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}

print(origins.items())

Output:

The items() method can be manipulated with the use of a for loop to get a key-value pair. You have to use the f string, which provides a way of putting Python expressions inside string literals, and these expressions get replaced by their values.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}
for key, value in origins.items():
    print(f"{key} : {value}")

Output:

Creating Nested Dictionaries

A nested dictionary is simply a dictionary within a dictionary, nothing more has to be said.

To access a particular value in a nested dictionary, you will not be able to use the get() method. You will have to use square brackets([]), which will contain the key associated with the item, that has another dictionary as its value. Besides the first set of square brackets, you will need another set of square brackets, which will contain the key in the nested dictionary. This code snippet below will make it all clearer:

players= {
    "player1": {
        "name": "ronaldo",
        "country": "portugal"
    },
    "player2": {
        "name": "messi",
        "country": "argentina"
    },
     "player3": {
         "name": "neymar",
         "country": "brazil"
    },
      "player4": {
          "name": "mbappe",
          "country": "france"
    }
}
print(players["player4"]["country"])

Output:

As you can see from the code above, there is a dictionary named players. Inside the players dictionary are nested dictionaries, that contain the names and countries of popular football players. Using the square brackets([]), you can get the required values.

Accessing Other Dictionary Methods

You can access all the Python dictionary's methods using the dir() method.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}
print(dir(origins))

Output:

You can also check the functions of all these methods using the help() method.

origins= {
    "ronaldo": "portugal",
    "messi": "argentina",
    "neymar": "brazil",
    "mbappe": "france"
}
print(help(origins))

Output:

Conclusion

Once understood perfectly, Python dictionaries can be easy to use and can be applied to a coding project.