×

Accessing Key-value in Dictionary in Python

A Python word reference is an assortment of key-esteem matches where each key is related to worth. Worth in the key-esteem pair can be a number, a string, a rundown, a tuple, or considerably another word reference. As a matter of fact, you can involve a worth of any substantial kind in Python as the worth in the key-esteem pair. A key in the key-esteem pair should be unchanging. As such, the key can't be changed, for instance, a number, a string, a tuple, and so on.

Python utilizes the wavy supports {} to characterize a word reference. Inside the wavy supports, you can put zero, one, or many key-esteem matches.

The accompanying model characterizes an unfilled word reference:

empty_dict = {}

Normally, you characterize an unfilled word reference before a circle, either for a circle or a while circle. Also, inside the circle, you add key-esteem matches to the word reference.

To find the sort of a word reference, you utilize the sort() capability as follows:

empty_dict = {}
print(type(empty_dict))

Ouptut:

Accessing Key-value in Dictionary in Python

The accompanying model characterizes a word reference with some key-esteem matches:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}

The individual word reference has five key-esteem coordinates that address the primary name, last name, age, most loved tones, and dynamic status.

Getting to values in a Dictionary

To get to a worth by key from a word reference, you can utilize the square section documentation or the get() strategy.

1) Using square section documentation

To get to a worth related with a key, you place the vital inside square sections:

dict[key]

The following shows how to get the values associated with the key first_name and last_name in the person dictionary:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
print(person['first_name'])
print(person['last_name'])

Output:

Accessing Key-value in Dictionary in Python

2) Using the get() method

If you attempt to access a key that doesn’t exist, you’ll get an error. For example:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}


ssn = person['ssn']

Error:

Accessing Key-value in Dictionary in Python

To avoid this error, you can use the get() method of the dictionary:

Person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
ssn = person.get('ssn')
print(ssn)

Output:

Accessing Key-value in Dictionary in Python

There is no such thing as on the off chance that the key, the get() technique returns None as opposed to tossing a KeyError. Note that None no method worth exists. The get() technique likewise returns default esteem when the key doesn't exist by, passing the default worth to its subsequent contention.

The accompanying model returns the '000-00-0000' string if the ssn key doesn't exist in the individual word reference:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
ssn = person.get('ssn', '000-00-0000')
print(ssn)

Output:

Accessing Key-value in Dictionary in Python

Adding new key-value pairs

Since a word reference has a powerful design, you can add new key-esteem matches to it whenever. To add another key-esteem pair to a word reference, you determine the name of the word reference followed by the new key in square sections alongside the new worth. The accompanying model adds another key-esteem pair to the individual word reference:

person['gender'] = 'Female'

Modifying values in a key-value pair

To change a worth related with a key, you determine the word reference name with the vital in square sections and the new worth related with the key:

dict[key] = new_value

The accompanying model changes the worth related with the age of the person dictionary:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
person['age'] = 26
print(person)

Output:

Accessing Key-value in Dictionary in Python

Removing key-value pairs

To eliminate a key-esteem pair by a key, you utilize the del explanation:

del dict[key]

In this language structure, you determine the word reference name and your desired key to eliminate.

The accompanying model eliminates the key 'active' from the person’s dictionary:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 26,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
del person['active']
print(person)

Output:

Accessing Key-value in Dictionary in Python

Looping through a dictionary

To look at a word reference, you can utilize a for the circle to emphasize its key-esteem coordinates, or keys, or values.

1) Looping all key-value pairs in a dictionary

Python word reference gives a strategy called items() that profits an item which contains a rundown of key-esteem matches as tuples in a rundown.

For instance:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
print(person.items())

Output:

Accessing Key-value in Dictionary in Python

To emphasize overall key-esteem matches in a word reference, you utilize a for a circle with two variable keys and worth to unload each tuple of the rundown:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
for key, value in person.items():
    print(f"{key}: {value}")

Output:

Accessing Key-value in Dictionary in Python

2) Looping through all the keys in a dictionary

Some of the time, you simply need to circle through all keys in a word reference. For this situation, you can utilize a circle with the keys() technique.

The keys() strategy returns an item that contains a rundown of keys in the word reference.

For instance:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
for key in person.keys():
    print(key)

Output:

Accessing Key-value in Dictionary in Python

In fact, looping through all keys is the default behaviour when looping through a dictionary. Therefore, you don’t need to use the keys() method.

The following code returns the same output as the one in the above example:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
for key in person:
    print(key)

Output:

Accessing Key-value in Dictionary in Python

3) Looping through all the values in a dictionary

The values() method returns a list of values without any keys. To loop through all the values in a dictionary, you use a for loop with the values() method:

person = {
    'first_name': 'Vikas',
    'last_name': 'Reddy',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
for value in person.values():
    print(value)

Output:

Accessing Key-value in Dictionary in Python

Outline

  • A Python word reference is an assortment of key-value matches, where each key has a related worth.
  • Utilize square sections or get() strategy to get to a worth by its vital.
  • Utilize the del proclamation to eliminate a key-value pair by the key from the word reference.
  • Use for loop to emphasize over keys, values, and key-value matches in a word reference.

Related Topics

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.

Python Variable Scope with Local & Non-local Examples

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Python delattr() function

Python delattr() function The delattr() function in Python is used to delete the named attribute from the object, with the prior permission of the object. Syntax delattr(object, name) Parameter object : This parameter represents the object from which...

1 minute read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Python Skyline

Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Glob

Methods for matching files that include particular patterns in accordance with UNIX shell-related expansion rules are referred to as "glob" methods. Similar methods for finding, locating, and searching for all of...

12 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Image to NumPy Arrays in Python

Image is a simple process of working model confined to machine learning, Python works with the image in the data format of width and height i.e. Images are excelled into...

3 minutes read.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Python property()

Python property() class The property() class in Python returns a property attribute. Syntax class property(fget=None, fset=None, fdel=None, doc=None) Parameter fget: This attribute is used for getting an attribute value. fset : This parameter sets an attribute value. fdel: It is a function for deleting...

1 minute read.

Make Notepad using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

5 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.