8
votes

Is there a more concise way of doing this in Python?:

def toDict(keys, values):
  d = dict()
  for k,v in zip(keys, values):
    d[k] = v

  return d
2
Along with the correct answers you've had so far for the technique, I'll point out that ‘to_dict’ is more Pythonic than ‘toDict’ when naming a function. See PEP 8 for the style recommendations for writing Python code. - bignose
+1 for helping someone who is clearly interested 'the way.' - physicsmichael
Thanks for the heads-up. However, this would rather belong in a wikified question along the lines of "Python coding style guidelines". - guillermooo

2 Answers

43
votes

Yes:

dict(zip(keys,values))
4
votes

If keys' size may be larger then values' one then you could use itertools.izip_longest (Python 2.6) which allows to specify a default value for the rest of the keys:

from itertools import izip_longest

def to_dict(keys, values, default=None):
    return dict(izip_longest(keys, values, fillvalue=default))

Example:

>>> to_dict("abcdef", range(3), 10)
{'a': 0, 'c': 2, 'b': 1, 'e': 10, 'd': 10, 'f': 10}

NOTE: itertools.izip*() functions unlike the zip() function return iterators not lists.