w3resource

Python: Get the key, value and item in a dictionary


31. Get Key, Value, and Item in a Dictionary

Write a Python program to get the key, value and item in a dictionary.

Visual Presentation:

Python Dictionary: Get the key, value and item in a dictionary.

Sample Solution:

Python Code:

# Create a dictionary 'dict_num' with keys and values.
dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

# Print a header for the output table.
print("key  value  count")

# Iterate through the key-value pairs in 'dict_num' using the 'enumerate' function.
# The 'enumerate' function assigns a count starting from 1 to each pair and unpacks them as (count, (key, value)).
for count, (key, value) in enumerate(dict_num.items(), 1):
    # Print the key, value, and count in a formatted table.
    print(key, '   ', value, '    ', count) 

Sample Output:

key  value  count                                                                                             
1     10      1                                                                                               
2     20      2                                                                                               
3     30      3                                                                                               
4     40      4                                                                                               
5     50      5                                                                                               
6     60      6

For more Practice: Solve these Related Problems:

  • Write a Python program to iterate over a dictionary and print each key along with its value using items().
  • Write a Python program to generate a list of tuples containing key and value pairs from a dictionary.
  • Write a Python program to use a for-loop to display each dictionary item on a separate line in the format "key: value".
  • Write a Python program to create a function that returns all key, value pairs as a list of strings formatted as "key = value".

Go to:


Previous: Write a Python program to get the top three items in a shop.
Next: Write a Python program to print a dictionary line by line.

Python Code Editor:

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.