Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 693
guillermooo Avatar asked Feb 23 '09 23:02

guillermooo


People also ask

Which function method is used for merging the new dictionary into the original dictionary?

Using method update(): Update() method is used to merge the second dictionary into the first dictionary without creating any new dictionary and updating the value of the first dictionary, whereas, the value of the second dictionary remains unaltered. Also, the function doesn't return any value. Example: Python3.

Can I use two dictionaries to merge?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries. Example: Python3.


2 Answers

Yes:

dict(zip(keys,values))
like image 142
MrTopf Avatar answered Oct 18 '22 14:10

MrTopf


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.

like image 32
jfs Avatar answered Oct 18 '22 13:10

jfs