w3resource

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

Python dictionary: Exercise-31 with Solution

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

Sample Solution:-

Python Code:

dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
print("key  value  count")
for count, (key, value) in enumerate(dict_num.items(), 1):
    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

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: How to make a chain of function decorators?

from functools import wraps

def makebold(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<b>" + fn(*args, **kwargs) + "</b>"
    return wrapped

def makeitalic(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<i>" + fn(*args, **kwargs) + "</i>"
    return wrapped

@makebold
@makeitalic
def hello():
    return "hello world"

@makebold
@makeitalic
def log(s):
    return s

print hello()        # returns "<b><i>hello world</i></b>"
print hello.__name__ # with functools.wraps() this returns "hello"
print log('hello')   # returns "<b><i>hello</i></b>"

Ref: https://bit.ly/3cVz5iw