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)
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)
You want the zip
function to make a generator of tuple
s 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.
Iterate through two lists simultaneously using zip
:
for key, value in zip(listKeys, listValues) :
dict[key] = value
Use zip:
for key, value in zip(listKeys, listValues): dict[key] = value