1

I have a list of keys and a list of values, I want to fill a dictionary so like:

 for key, value in listKeys, listValues:
     dict[key] = value

However, I get the following error:

builtins.ValueError: too many values to unpack (expected 2)
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Jet Alex
  • 49
  • 1
  • 1
  • 6

3 Answers3

8

You want the zip function to make a generator of tuples of values from each of a number of inputs:

mydict = {}
for key, value in zip(listKeys, listValues):
     mydict[key] = value

That said, you could skip the rigmarole of writing your own loop and let the dict constructor do the work; it can take an iterable of key/value pairs to initialize itself, and avoid the Python level loop entirely:

mydict = dict(zip(listKeys, listValues))

or if mydict is an existing non-empty dict, use the update method, which accepts the same arguments as the constructor:

mydict.update(zip(listKeys, listValues))

Side-note: I renamed your variable to mydict, because shadowing built-in names like dict is a terrible, terrible idea.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
2

Iterate through two lists simultaneously using zip :

for key, value in zip(listKeys, listValues) :
    dict[key] = value
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • thanks, i appreciate the quick response – Jet Alex Nov 29 '16 at 04:04
  • 1
    If you see a very common question with a popular canonical duplicate, you can vote or flag the question for closure with that duplicate. – TigerhawkT3 Nov 29 '16 at 04:11
  • Why a down-vote ?! My reputation is not enough to do this, and down-voting is no way to give this information, a single comment is enough. Please lift the down-vote. @TigerhawkT3 – Jarvis Nov 29 '16 at 04:11
  • You can flag a question for closure as a duplicate [with 15 reputation](http://stackoverflow.com/help/privileges/flag-posts). – TigerhawkT3 Nov 29 '16 at 04:14
  • Thanks for this info, but my point is down-voting others' answer just to "punish" them for not knowing this info, is not OKAY. We all are learners here. @TigerhawkT3 – Jarvis Nov 29 '16 at 04:15
  • Yes, it looks like someone downvoted your answer. Whoever did so must have felt that it wasn't useful (as suggested by the tooltip). However, votes are anonymous, so we may never know who voted this way. – TigerhawkT3 Nov 29 '16 at 04:20
1

Use zip:

for key, value in zip(listKeys, listValues): dict[key] = value

happydave
  • 7,127
  • 1
  • 26
  • 25