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
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read