How to Access dict Attribute in Python
Last Updated :
26 Mar, 2024
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": "[email protected]"
}
# Access and print attributes from the dictionary
print("Name: ", student["name"])
print("Age: ", student["age"])
print("City: ", student["city"])
print("Email: ", student["email"])
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)
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
OutputRohan
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
Outputdict_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
Outputdict_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
Outputdict_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.
Similar Reads
How to Create a Dictionary in Python
The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
How to Get a List of Class Attributes in Python?
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
4 min read
Python - Access Parent Class Attribute
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
4 min read
How to Change Class Attributes in Python
In Python, editing class attributes involves modifying the characteristics or properties associated with a class. Class attributes are shared by all instances of the class and play an important role in defining the behavior and state of objects within the class. In this article, we will explore diff
3 min read
How to Add Attributes in Python Metaclass?
This article explains what a metaclass is in the Python programming language and how to add attributes to a Python metaclass. First, let's understand what a metaclass is. This is a reasonably advanced Python topic and the following prerequisites are expected You have a good grasp of Python OOP Conce
4 min read
How to Alphabetize a Dictionary in Python
Alphabetizing a dictionary in Python can be useful for various applications, such as data organization and reporting. In this article, we will explore different methods to alphabetize a dictionary by its keys or values. Dictionary OrderingIn Python, dictionaries are a powerful data structure that al
3 min read
Accessing Attributes and Methods in Python
In Python, attributes and methods define an object's behavior and encapsulate data within a class. Attributes represent the properties or characteristics of an object, while methods define the actions or behaviors that an object can perform. Understanding how to access and manipulate both attributes
4 min read
Dynamic Attributes in Python
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
How to Print Object Attributes in Python
In Python, objects are the cornerstone of its object-oriented programming paradigm. An object is an instance of a class, and it encapsulates both data (attributes) and behaviors (methods). Understanding how to access and print the attributes of an object is fundamental for debugging, inspecting, and
2 min read
dict() Constructor in Python
In Python, the dict() constructor is used to create a dictionary object. A dictionary is a built-in data type that stores data in key-value pairs, similar to a real-life dictionary where each word (the key) has a meaning (the value). The dict() constructor helps you create empty dictionaries or conv
2 min read