Как вывести словарь в python
Перейти к содержимому

Как вывести словарь в python

  • автор:

Python – Print Dictionary

To print dictionary items: key:value pairs, keys, or values, you can use an iterator for the corresponding key:value pairs, keys, or values, using dict.items(), dict.keys(), or dict.values() respectively and call print() function.

In this tutorial, we will go through example programs, to print dictionary as a single string, print dictionary key:value pairs individually, print dictionary keys, and print dictionary values.

1. Print Dictionary as a single string

To print whole Dictionary contents, call print() function with dictionary passed as argument. print() converts the dictionary into a single string literal and prints to the standard console output.

In the following program, we shall initialize a dictionary and print the whole dictionary.

Python Program

Output

2. Print Dictionary key:value pairs

To print Dictionary key:value pairs, use a for loop to traverse through the key:value pairs, and use print statement to print them. dict.items() returns the iterator for the key:value pairs and returns key, value during each iteration.

In the following program, we shall initialize a dictionary and print the dictionary’s key:value pairs using a Python For Loop.

Python Program

Output

3. Print Dictionary keys

To print Dictionary keys, use a for loop to traverse through the dictionary keys using dict.keys() iterator, and call print() function.

In the following program, we shall initialize a dictionary and print the dictionary’s keys using a Python For Loop.

Python Program

Output

4. Print Dictionary values

To print Dictionary values, use a for loop to traverse through the dictionary values using dict.values() iterator, and call print() function.

In the following program, we shall initialize a dictionary and print the dictionary’s values using a Python For Loop.

Python Program

Output

Summary

In this tutorial of Python Examples, we learned how to print Dictionary, its key:value pairs, its keys or its values.

Printing Dictionary in Python

A dictionary is a data structure that stores key-value pairs. When you print a dictionary, it outputs pairs of keys and values.

Let’s take a look at the best ways you can print a dictionary in Python.

Print dictionary

The content of a Python dictionary can be printed using the print() function.

If you run the code, Python is going to return the following result:

Both keys and values are printed.

You can also use the dictionary method called items().

This function will display key-value pairs of the dictionary as tuples in a list.

Printing with the for loop

items() can be used to separate dictionary keys from values. Let’s use the for loop to print the dictionary line by line.

If you run the code, the key-value pair will be printed using the print() function.

Print keys and values separately

With the items() method, you can print the keys and values separately.

for keys:

for values:

Python offers additional methods keys() and values() methods to achieve the same result.

keys() method:

values() method:

Using list comprehension to print dictionary

With a list comprehension, we can print a dictionary using the for loop inside a single line of code.

This code will return the contents of a dictionary line by line.

In a similar manner, you can also do list comprehension with keys() and values().

Output:

Prettyprint dictionaries as a table

If a dictionary becomes more complex, printing it in a more readable way can be useful. This code will display the dictionary as a table.

Inside the new dictionary, four elements represent multiple cars. The first part is a key, and the second part (value) is a list consisting of the brand of a car, its model, and its year of production.

The first print() function displays four headers: “Key”, “Brand”, “Model”, “Year”. Each of them is spaced by the number of characters from the previous column.

The same is done to the dictionary items. Each value is a list assigned to three variables: brand, model, and year, with the same amount of spacing.

If you run the code, you’ll see a dictionary displayed in a pretty tabular form.

How to print out a dictionary nicely in Python?

I’ve just started to learn python and I’m building a text game. I want an inventory system, but I can’t seem to print out the dictionary without it looking ugly.

This is what I have so far:

codeforester's user avatar

Raphael Huang's user avatar

10 Answers 10

I like the pprint module (Pretty Print) included in Python. It can be used to either print the object, or format a nice string version of it.

But it sounds like you are printing out an inventory, which users will likely want shown as something more like the following:

My favorite way:

Here’s the one-liner I’d use. (Edit: works for things that aren’t JSON-serializable too)

Explanation: This iterates through the keys and values of the dictionary, creating a formatted string like key + tab + value for each. And "\n".join(. puts newlines between all those strings, forming a new string.

Как распечатать элементы словаря в Python

Чтобы напечатать элементы словаря пары ключ:значение, вы можете использовать dict.items(), dict.keys() или dict.values.(), функцию print().

В этом руководстве мы рассмотрим примеры программ, чтобы напечатать словарь как одну строку, словарь пары ключ:значений по отдельности, ключи словаря и значения словаря.

Распечатать словарь, как одну строку

Чтобы распечатать все содержимое словаря, вызовите функцию print() со словарем, переданным в качестве аргумента. print() преобразует словарь в одностроковый литерал и выводит на стандартный вывод консоли.

В следующей программе мы инициализируем словарь и распечатаем его целиком.

Как распечатать пары ключ:значение?

Чтобы распечатать пары ключ:значение в словаре, используйте цикл for и оператор печати для их печати. dict.items() возвращает итератор для пар ключ:значение во время каждой итерации.

В следующей программе мы инициализируем словарь и распечатаем пары ключ:значение словаря с помощью цикла For Loop.

Печать ключей словаря

Чтобы напечатать ключи словаря, используйте цикл for для обхода ключей с помощью итератора dict.keys() и вызова функции print().

В следующей программе мы инициализируем словарь и распечатаем ключи словаря с помощью For Loop.

Печать значения словаря

Чтобы распечатать значения словаря, используйте цикл for для просмотра значений словаря с помощью итератора dict.values() и вызова функции print().

В следующей программе мы инициализируем словарь и распечатаем значения словаря с помощью For Loop.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *