Accessing Key-value in a Python Dictionary

PythonProgrammingServer Side Programming

While analyzing data using Python data structures we will eventually come across the need for accessing key and value in a dictionary. There are various ways to do it in this article we will see some of the ways.

With for loop

Using a for loop we can access both the key and value at each of the index position in dictionary as soon in the below program.

Example

 Live Demo

dictA = {1:'Mon',2:'Tue',3:'Wed',4:'Thu',5:'Fri'}
#Given dictionary
print("Given Dictionary: ",dictA)
# Print all keys and values
print("Keys and Values: ")
for i in dictA :
   print(i, dictA[i])

Output

Running the above code gives us the following result −

Given Dictionary: {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri'}
Keys and Values:
1 Mon
2 Tue
3 Wed
4 Thu
5 Fri

With list comprehension

In this approach we consider the key similar to an index in a list. So in the print statement we represent the keys and the values as a pair along with the for loop.

Example

 Live Demo

dictA = {1:'Mon',2:'Tue',3:'Wed',4:'Thu',5:'Fri'}
#Given dictionary
print("Given Dictionary: ",dictA)
# Print all keys and values
print("Keys and Values: ")
print([(k, dictA[k]) for k in dictA])

Output

Running the above code gives us the following result −

Given Dictionary: {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri'}
Keys and Values:
[(1, 'Mon'), (2, 'Tue'), (3, 'Wed'), (4, 'Thu'), (5, 'Fri')]

With dict.items

The dictionary class has a method named items. We can access the items method and iterate over it getting each pair of key and value.

Example

 Live Demo

dictA = {1:'Mon',2:'Tue',3:'Wed',4:'Thu',5:'Fri'}
#Given dictionary
print("Given Dictionary: ",dictA)
# Print all keys and values
print("Keys and Values: ")
for key, value in dictA.items():
   print (key, value)

Output

Running the above code gives us the following result −

Given Dictionary: {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri'}
Keys and Values:
1 Mon
2 Tue
3 Wed
4 Thu
5 Fri
raja
Published on 09-Jul-2020 12:36:07
Advertisements