How to print keys and values in a dictionary? Wait.. what is a dictionary?
In the Python programming language, a dictionary is a one to one mapping. Its a set of key-value pairs. Each key is mapped to one and only one value.
You can run two key operations on a dictionary: store a value with some key and extract the value given the key.
In other programming languages a dictionary is sometimes called "associative memories" or "associative arrays".
Example
In Python, an empty dictionary would be defined with curly brackets.
x = {}
Do not confuse with lists, which use another type of brackets [].
A simple dictionary would be defined like this, with every pair separated by a comma and every key-value pair linked using a colon:
my_dict = { "name":"Alicia", "city":"Toronto", "country":"Canada"}
Print dictionary with for loop
One way to print the values in a dictionary is to use a for loop.
import json
my_dict = { "name":"Alicia", "city":"Toronto", "country":"Canada"}
for item in my_dict:
print("({}->{})".format(item,my_dict[item]))
The program then outputs the key->value mapping for each pair in the dictionary:
(city->Toronto)
(name->Alicia)
(country->Canada)
Print dictionary with item() method
You can use the .items() method to get the key,value from a dictionary. In my opinion this is easier to read.
This also has the advantage of having both the key and value available in a clear way inside the for loop. It's good for readability of your program.
import json
my_dict = { "name":"Alicia", "city":"Toronto", "country":"Canada"}
for key,value in my_dict.items():
print("({}->{})".format(key,value))
Print using keys
Another way to output a dictionary is to get all keys and use the keys to output the key-value pairs.
In every iteration, the key is used to get the value in the dictionary. Note that this is the same as the first method, but with explicit definition of key.
import json
my_dict = { "name":"Alicia", "city":"Toronto", "country":"Canada"}
for key in my_dict.keys():
print("({}->{})".format(key,my_dict[key]))
Related links:
Top comments (1)
Nice but please use f-strings!