Как собрать словарь из двух списков python циклом for
Перейти к содержимому

Как собрать словарь из двух списков python циклом for

  • автор:

Списки в словари: трансформация данных в Python

Иногда во время работы с Python перед программистом возникает задача создания словаря из двух списков. Данная статья предназначена для помощи в решении данной задачи с применением различных методов, которые справляются с этой проблемой эффективно и элегантно. Прежде чем перейти к рассмотрению этих методов, предполагается, что вы уже знакомы с основными концепциями списков и словарей в Python.

Основной метод: функция zip()

Первый и самый базовый способ создания словаря из двух списков в Python — это использование встроенной функции zip() вместе с функцией dict() . Допустим, у нас есть два списка:

Мы можем создать словарь из этих двух списков следующим образом:

Функция zip() принимает два или более итерируемых объекта (в данном случае — списки) и возвращает итератор кортежей, где первый элемент каждого переданного итератора объединен вместе, затем второй элемент каждого переданного итератора объединен вместе и т. д.

Использование генераторов словарей

Генераторы словарей представляют собой эффективный и элегантный способ создания словарей в Python. Они возвращают генератор, который можно преобразовать в словарь. Давайте используем наши списки ключей и значений из предыдущего примера:

Этот код делает то же самое, что и предыдущий пример, но использует генератор словарей, что делает его более коротким и лаконичным.

Создание словаря с помощью цикла for

Вы также можете использовать цикл for для создания словаря из двух списков. Это может быть полезно, если у вас есть какая-то дополнительная логика, которую вы хотите применить при создании словаря. Допустим, вы хотите умножить каждое значение на 2 перед добавлением его в словарь. Вот как вы можете сделать это:

Создание словаря с помощью метода fromkeys()

Если у вас есть список ключей и вы хотите создать словарь, где все значения инициализированы одинаковым значением, вы можете использовать метод fromkeys() класса dict. Вот как вы можете сделать это:

Этот метод полезен, когда вы заранее знаете ключи вашего словаря и хотите инициализировать все их значения одинаковым значением.

Заключение

В Python есть множество способов создания словаря из двух списков, включая функцию zip() , генераторы словарей, циклы for и метод fromkeys() . В зависимости от вашей конкретной задачи и предпочтений, вы можете выбрать любой из этих методов для эффективного создания словарей.

Python: Create Dictionary From Two Lists

Python Create a Dictionary from Two Lists Cover Image

In this post, you’ll learn how to use Python to create a dictionary from two lists. You’ll learn how to do this with the built-in zip() function, with a dictionary comprehension, and a naive for loop method. Finally, you’ll learn which of these methods is the best for highest performance.

The Quick Answer:

Table of Contents

Covert Two Lists into a Dictionary with Python Zip

The Python zip() function is an incredibly helpful function to make iterating or multiple iterators much easier. To learn about the zip() function a bit more, check out my in-depth tutorial on zipping multiple Python lists.

Let’s see how we can use the zip() function to convert two Python lists into a dictionary:

Let’s see what we’ve done here:

  1. We declared two lists, names and ages , which contains people’s names and their ages
  2. We use the zip() function to turn this into a zip object containing tuples of the corresponding names and ages
  3. Finally, we use the dict() function to convert the zip object into a dictionary, where the tuples are mapped as (key, value)

In the following section, you’ll learn how to use a dictionary comprehension to convert two Python lists into a dictionary.

Covert Two Lists into a Dictionary with a Dictionary Comprehension

Dictionary comprehensions are a fun way to loop over items and create a resulting dictionary. To learn more about dictionary comprehensions, check out my in-depth tutorial here.

Python Dictionary Comprehension overview

Let’s work with the two lists that we worked with above and use a Python dictionary comprehension to create a dictionary:

The way that this dictionary comprehension works is as below:

  1. We loop over the range(len(names)), meaning that we loop over the numbers 0 through 2.
  2. We assign the dictionary key the index item of the names list
  3. We assign the dictionary value the index item of the ages list

Dictionary comprehensions can be a bit tricky to get a hang of, but they are fun to write!

Covert Two Lists into a Dictionary with a For Loop

Wherever you can use a comprehension, you can also use a for-loop. Let’s see how we can loop over two lists to create a Python dictionary out of the two lists.

We will want to loop over the range() of the length of one of the lists and access the items.

Let’s give this a try and see how we can build on it:

Let’s explore what we’ve done here:

  1. We create an empty dictionary using the dict() function
  2. We loop over each in the range() function
  3. We access the value of the names index and assign it to the variable key
  4. We do the same for the ages list and assign it to value
  5. We assign the dictionary key and value using direct assignment

We can also simplify this quite a bit by simply not assigning the variables first:

Now that you’ve learned how to combine two lists into a dictionary, let’s find out which of these methods is the one with the best performance!

What is the Most Efficient Way to Covert Two Lists into a Dictionary?

Now that you have learned three different methods to turn two Python lists into a dictionary, let’s see which of these methods has the highest performance.

We can create a decorator to time these items and quickly turn them into functions:

From this, we can see that the zip() function method is significantly faster. It also happens to be more memory efficient since it only loads the data as it needs to!

Conclusion

In this post, you learned three different ways two turn two Python lists into a dictionary. You learned how to accomplish this using the built-in zip() function, a dictionary comprehension, and a for loop. You also learned that the zip() function is the most efficient way of doing this, saving you nearly 3/4 of the time.

To learn more about the Python zip function, check out the official documentation here.

Как создать словарь из двух списков в Python

В Python есть несколько способов создания словаря из двух списков. Здесь мы рассмотрим три основных метода.

1. Используя функцию zip()

Функция zip() принимает итерируемые объекты (массивы, строки и т.д.) и возвращает итератор кортежей, где каждый кортеж состоит из пары элементов.

2. Используя цикл for

Цикл for можно использовать для прохода по обоим спискам одновременно и добавления элементов в словарь.

3. Используя dictionary comprehension

Dictionary comprehension — это эффективный и ясный способ создания словаря из двух списков.

Выбор метода зависит от ваших требований и предпочтений. Каждый из этих методов даст вам словарь из двух списков.

Как сделать словарь из двух списков?

Итак , у меня есть два списка uniq и fifa(по длине одинаковы). Мне нужно , чтобы каждому элементу списка uniq был наследован каждый элемент списка uniq.

p.s. к глубочайшему сожалению , я не могу придумать , как сделать данную конструкцию без костылей

MaxU - stand with Ukraine's user avatar

Sahar Vkusni's user avatar

Судя по описанию задачи и метке Pandas вам нужен Pandas.Series:

MaxU - stand with Ukraine's user avatar

Для того, чтобы из двух списков сделать словарь, надо перебрать в цикле все индексы любого из списков (ведь длина списков одинакова):

Теперь в теле цикла можно обратиться к элементам с одинаковыми индексами: uniq[i] и fifa[i] — это ключ и значение элемента словаря, который нужно создать. Создать новый элемент словаря можно так: uniq_and_fifa[ключ] = значение . Объявляем пустой словарь и дописываем цикл for :

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

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