×

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

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

How to Declare a Variable in Python?

The concept of constants and variables is something that we are studying right from our primary classes. We know that constants are the fixed values whereas variables are those whose...

4 minutes read.

How to print in the same line in Python?

How to print in the same line in python By default, the print function in Python takes us to the next line and prints the desired statement in the output. In this...

5 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

Python Switch Case

What is a Switch Case Statement? In the programming languages, a switch statement is a logical loop or syntax that tests the variable's value and compares it with multiple cases. Once...

3 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.