What Is Map Data Type in Python?

//

Heather Bennett

What Is Map Data Type in Python?

In Python, a map is a built-in data type that allows you to store key-value pairs. It is also known as a dictionary or associative array in other programming languages. Maps are incredibly useful when you need to store and retrieve data based on unique keys rather than numeric indices.

Creating a Map

To create a map in Python, you can use curly braces ({}) or the built-in dict() function. Let’s take a look at some examples:


# Using curly braces
my_map = {'name': 'John', 'age': 25, 'country': 'USA'}

# Using dict() function
my_map = dict(name='John', age=25, country='USA')

In both cases, we have created a map with three key-value pairs: ‘name’ with the value ‘John’, ‘age’ with the value 25, and ‘country’ with the value ‘USA’.

Accessing Values in a Map

To access values in a map, you can use square brackets ([]). Let’s see how it works:


my_map = {'name': 'John', 'age': 25, 'country': 'USA'}

print(my_map['name'])  # Output: John
print(my_map['age'])   # Output: 25
print(my_map['country'])  # Output: USA

In this example, we access the values of keys ‘name’, ‘age’, and ‘country’ using square brackets and print them to the console.

Modifying a Map

Maps in Python are mutable, which means you can modify their values or add new key-value pairs after creation. Let’s see some examples:

# Modifying a value
my_map[‘age’] = 30

# Adding a new key-value pair
my_map[‘city’] = ‘New York’

print(my_map)

The output will be:


{'name': 'John', 'age': 30, 'country': 'USA', 'city': 'New York'}

In this example, we modify the value of the ‘age’ key to 30 and add a new key-value pair ‘city’ with the value ‘New York’.

Iterating Over a Map

You can iterate over the keys or values of a map using loops. Let’s see how it works:

# Iterating over keys
for key in my_map:
print(key)

# Iterating over values
for value in my_map.values():
print(value)

# Iterating over key-value pairs
for key, value in my_map.items():
print(key, value)

The output will be:


name
age
country

John
25
USA

name John
age 25
country USA

In these examples, we use different loops to iterate over keys, values, and key-value pairs of the map.

Checking if a Key Exists

You can check if a specific key exists in a map using the in keyword. Here’s an example:

if ‘name’ in my_map:
print(‘Key exists’)
else:
print(‘Key does not exist’)


Key exists

In this example, we check if the key ‘name’ exists in the map and print the corresponding message.

Conclusion

In Python, maps are a powerful data type that allows you to store and retrieve data based on unique keys. With their ability to hold key-value pairs, maps provide efficient ways to organize and manipulate data in your programs.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy