7

I tried this:

numbers_dict = dict()
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]
numbers_dict[name for name in name_list] = num for num in num_list

And as a result I got this exception:

File "<stdin>", line 1
numbers_dict[name for name in name_list] = num for num in num_list
Python
  • 127
  • 1
  • 14

6 Answers6

7

You don't need to explicitly loop. You can use zip to join your two lists and then wrap it in a dict for the result you're looking for:

>>> dict(zip(num_list, name_list))

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
fordy
  • 2,520
  • 1
  • 14
  • 22
2

You are trying to mix list comprehensions, for loops and multiple key access into a single expression. This, unfortunately, is not possible in Python. Choose one method and stick with it.

Here are some options. They all involve zip, which returns elements from each argument iterable sequentially.

for loop

d = {}
for k, v in zip(name_list, num_list):
    d[k] = v

dictionary comprehension

d = {k: v for k, v in zip(name_list, num_list)

dict constructor

d = dict(zip(name_list, num_list))
jpp
  • 159,742
  • 34
  • 281
  • 339
2

Use zip - https://www.programiz.com/python-programming/methods/built-in/zip.

numbers_dict = dict()
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]

numbers_dict = dict(zip(name_list, num_list))

then print(numbers_dict) gives {'one': 1, 'two': 2, 'three': 3, 'four': 4}.

PythonParka
  • 134
  • 3
  • 13
2

You NEED to use the For Loop? So just:

for i in range(len(num_list)):
    numbers_dict[num_list[i] = name_list[i]]

But the best tool you could use is zip:

numbers_dict = zip(num_list, name_list)

Lodi
  • 565
  • 4
  • 16
1

There are comprehensions for dict as well as for list. The dict ones look like the literal syntax:

{key: value for key, value in iterable}

In your case zip is probably the right tool:

>>> num_list = range(1, 5)
>>> name_list = ['one', 'two', 'three', 'four']
>>> zip(num_list, name_list)
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> dict(_)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
1

You can also use pandas:

numbers_series = pd.Series(name_list,index=num_list)

A pandas series acts much like a dictionary, but if you really want it in dictionary form, you can do numbers_dict = dict(numbers_series).

Acccumulation
  • 3,491
  • 1
  • 8
  • 12
  • And you could use a thermonuclear device to kill mosquitoes. :) Pandas is fine when the OP is asking for a Pandas solution, or if they have a lot of data to process, but it's overkill when the OP just wants to turn a pair of small lists into a dict. – PM 2Ring Jul 04 '18 at 10:23