w3resource

Python: Access dictionary key’s element by index


55. Access Dictionary Key's Element by Index

Write a Python program to access dictionary key's element by index.

Visual Presentation:

Python List: Access dictionary key’s element by index.

Sample Solution:

Python Code:

# Create a dictionary 'num' with subject names as keys and corresponding marks as values.
num = {'physics': 80, 'math': 90, 'chemistry': 86}

# Print a message indicating the intention to access the keys of the dictionary and retrieve them as a list.
print("\nAccess the keys of the dictionary as a list:")

# Access and print the first key (subject name) in the dictionary.
print(list(num)[0])

# Access and print the second key (subject name) in the dictionary.
print(list(num)[1])

# Access and print the third key (subject name) in the dictionary.
print(list(num)[2])

Sample Output:

Access the keys of the dictionary as a list:
physics
math
chemistry

Flowchart:

Flowchart: Get the depth of a dictionary

For more Practice: Solve these Related Problems:

  • Write a Python program to retrieve a dictionary key by converting the keys to a list and accessing the nth element.
  • Write a Python program to implement a function that returns the key at a specified index from a dictionary.
  • Write a Python program to sort the dictionary keys and then return the key at a given index.
  • Write a Python program to iterate over a dictionary with enumerate() and output the key when the index matches the input value.

Python Code Editor:

Previous: Get the depth of a dictionary.
Next: Convert a given dictionary into a list of lists.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.