Python print dictionary keys and values | Example code

The simple and most used method is “in operator” to get dictionary keys and values in Python. Once you have dit keys and values then print them one by one within a for-loop.

Example print dictionary keys and values in Python

Simple example code.

dict1 = {"A": 10, "B": 20, "C": 30}

for i in dict1:
    print(i, dict1[i])

Output:

Using list comprehension

This method returns the key-value pairs of dictionaries as tuples of key and value in the list.

dict1 = {"A": 10, "B": 20, "C": 30}

print([(k, dict1[k]) for k in dict1])

Output: [(‘A’, 10), (‘B’, 20), (‘C’, 30)]

Using dict.items()

The items() function in the dictionary iterates over all the keys to access dictionary keys with value.

dict1 = {"A": 10, "B": 20, "C": 30}

for key, value in dict1.items():
    print(key, value)

Output:

A 10
B 20
C 30

Using enumerate()

With this method access the named index of the position of the pair in the dictionary.

dict1 = {"A": 10, "B": 20, "C": 30}

for i in enumerate(dict1.items()):
    print (i)

Output:

(0, (‘A’, 10))
(1, (‘B’, 20))
(2, (‘C’, 30))

Do comment if you have any doubts and suggestions on this Python dict tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.