Open In App

How to Access dict Attribute in Python

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, A dictionary is a type of data structure that may be used to hold collections of key-value pairs. A dictionary’s keys are connected with specific values, and you can access these values by using the keys. When working with dictionaries, accessing dictionary attributes is a basic function because it allows you to retrieve and modify the data stored within the dictionary.

In this article, we will discuss How to Access dict Attribute in Python using various methods.

Example: In this code a dictionary named a student with keys such as “name,” “age,” “city,” and “email,” each corresponding to specific attributes. The print statements then access and print the values associated with each key in the student dictionary.

Python3
# Define a dictionary to store attributes of a person
student = {
    "name": "Rahul",
    "age": 20,
    "city": "New Delhi",
    "email": "rahul@gmail.com"
}

# Access and print attributes from the dictionary
print("Name: ", student["name"])
print("Age: ", student["age"])
print("City: ", student["city"])
print("Email: ", student["email"])

Output
Name: Rahul
Age: 20
City: New Delhi
Email: rahul@gmail.com


We define a dictionary called “student” for the record of a student’s characteristics, such as name, age, city, and email address. Every attribute in the dictionary is a key-value pair.

To retrieve and publish the values related to particular keys (like “name” and “age”) in the student dictionary, we enclose them in square brackets and send them to the console.

Various methods to access a dictionary attribute in Python

Using Square Brackets

A dictionary’s items can be accessed by using the key name, which is contained in square brackets.

Example: We have a have a dictionary named this_dict with keys “name,” “age,” and “city,” each associated with specific values. You use square brackets to access the values associated with the keys and assign them to variables (name, age, city) then print the values

Python3
this_dict = {"name": "Rohan", "age": 30, "city": "New Delhi"}
# Access values using square brackets
name = this_dict["name"]
age = this_dict["age"]
city = this_dict["city"]
print(name)
print(age)
print(city)

Output
Rohan
30
New Delhi


Using the get() Method

When the key is not found, the get() method allows you to retrieve dictionary attributes without creating a KeyError. It simply returns the default value.

Example : In this example, you use this_dict.get(“name”) to retrieve the value associated with the key “name” and assign it to the variable name. Similarly, you do the same for “age” and “city.” values stored in name, age, and city are printed to the console.

Python3
this_dict = {"name": "Rohan", "age": 30, "city": "New Delhi"}
# Access values using the get() method
name = this_dict.get("name") 
age = this_dict.get("age")   
city = this_dict.get("city") 
print(name) 
print(age) 
print(city)
# Accessing a key that doesn't exist with get() (no KeyError)
country = this_dict.get("country")
print(country)  # This will print None since "country" is not a key in the dictionary

Output
Rohan
30
New Delhi
None


Using the keys() Method

The keys() method returns a list of the dictionary’s keys. This can be useful when you need to iterate over the keys or check for the existence of a particular key.

Example: The line x = laptop.keys() uses the keys() method to retrieve a view object that displays a list of all the keys in the laptop dictionary. The keys() method returns a view object that reflects changes made to the dictionary. It does not create a new list but provides a dynamic view of the keys.

Python3
laptop = {
    "brand": "Hp",
    "model": "Hp98756R",
    "year": 2020
}
x = laptop.keys()
print(x)  # This will print the keys of the dictionary before adding a new key-value pair

laptop["color"] = "Grey"
print(x)  # This will print the keys of the dictionary after the new key-value pair is added

Output
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])


Using the values() Method

The values() method returns a list of all the values in the dictionary. It is handy when you want to inspect or manipulate the values independently of their associated keys.

Example: In this code we used The line x = laptop.values() uses the values() method to retrieve a view object that displays a list of all the values in the laptop dictionary. The values() method returns a view object that reflects changes made to the dictionary. It provides a dynamic view of the values.

Python3
laptop = {
    "brand": "Dell",
    "model": "D6765Td",
    "year": 2022
}
x = laptop.values()
print(x)  # This will print the values of the dictionary before adding the new key-value pair

laptop["color"] = "black"
print(x)  # This will print the values of the dictionary after the new key-value pair is added

Output
dict_values(['Dell', 'D6765Td', 2022])
dict_values(['Dell', 'D6765Td', 2022, 'black'])


Using the items() Method

The items() method returns a list of tuples, each containing a key-value pair from the dictionary. This is useful for iterating over both keys and values simultaneously.

Example: In this code, line x = laptop.items() uses the items() method to retrieve a view object that displays a list of tuples containing key-value pairs from the laptop dictionary. The items() method returns a view object reflecting the items (key-value pairs) of the dictionary.

Python3
laptop = {
    "brand": "Dell",
    "model": "D6765Td",
    "year": 2022
}
x = laptop.items()
print(x)  # Displays the key-value pairs before adding a new key-value pair

laptop["color"] = "black"
print(x)  # Reflects the updated dictionary, including the new key-value pair

Output
dict_items([('brand', 'Dell'), ('model', 'D6765Td'), ('year', 2022)])
dict_items([('brand', 'Dell'), ('model', 'D6765Td'), ('year', 2022), ('color', 'black')])


Using the map() Function

The map() function applies a given function to each item of an iterable (e.g., a dictionary) and returns a list of the results.

Example: In this code, we use the map() function to transform each key-value pair in the laptop dictionary into a tuple where the key is the first element and the value is a list containing the second element. The result is stored as a list of dictionaries.

Python
# Nikunj Sonigara
laptop = {
    "brand": "Dell",
    "model": "D6765Td",
    "year": 2022
}

# Update the dictionary
laptop["color"] = "black"

# Using map to create a list of dictionaries
list_of_dicts = [dict(map(lambda item: (item[0], [item[1]]), laptop.items()))]

# Print the output
print(list_of_dicts)

Output
[{'color': ['black'], 'brand': ['Dell'], 'model': ['D6765Td'], 'year': [2022]}]

Conclusion

By understanding various methods for accessing and manipulating dictionaries enhances the capability of working with structured data in Python. These particular examples showcase practical applications of dictionaries, how they can be used to represent and access information efficiently in Python.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads