0

Let's be concise:

keys = ['a', 'b']
values = [1, 2]
d = the_function_i_m_looking_for(keys, values)
# d = {'a': 1, 'b': 2}

Can you put a name for the_function_i_m_looking_for?

AsTeR
  • 7,247
  • 14
  • 60
  • 99
  • possible duplicate of [Map two lists into a dictionary in Python](http://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python) – Graeme Stuart Sep 17 '13 at 20:52
  • @GraemeStuart it's a duplicate indeed, I didn't found that one since I kept using the words "array" when python is about "list" – AsTeR Sep 17 '13 at 21:21

3 Answers3

3

One of many possible ways is:

{k: v for k, v in zip (keys, values) }

Another would be:

dict (zip (keys, values) )

Hence:

def the_function_you_are_looking_for (keys, values):
    return dict (zip (keys, values) )
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
2

You can do this using zip to make key: value pairs and pass them into dict()

dict(zip(keys, values))

I don't know of a function that does this in one go.

This is a duplicate of this question.

Community
  • 1
  • 1
Graeme Stuart
  • 5,837
  • 2
  • 26
  • 46
1

The function you are looking for is zip paired with the dict constructor.

keys = ['a', 'b']
values = [1, 2]

d = dict(zip(keys, values))

print(d)

Result:

{'a': 1, 'b': 2}

For large lists you may want to use itertools.izip

If your key / value lists are different sizes izip_longest with a default value.

Serdalis
  • 10,296
  • 2
  • 38
  • 58