What's the Pythonic way to combine two sequences into a dictionary?

前端 未结 2 1289
夕颜
夕颜 2020-12-16 22:28

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条回答
  • 2020-12-16 22:41

    Yes:

    dict(zip(keys,values))
    
    0 讨论(0)
  • 2020-12-16 22:51

    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.

    0 讨论(0)
提交回复
热议问题