Building a dictionary from a tuple of variable length

Peter Otten __peter__ at web.de
Mon Mar 5 09:55:27 CET 2007


bg_ie at yahoo.com wrote:

> I have the following tuple -
> 
> t = ("one","two")
> 
> And I can build a dictionary from it as follows -
> 
> d = dict(zip(t,(False,False)))
> 
> But what if my tuple was -
> 
> t = ("one","two","three")
> 
> then I'd have to use -
> 
> d = dict(zip(t,(False,False,False)))
> 
> Therefore, how do I build the tuple of Falses to reflect the length of
> my t tuple?

For dictionaries there is a special method:

>>> dict.fromkeys(("one", "two", "three"), False)
{'three': False, 'two': False, 'one': False}

When you are just interested in the list of tuples, use repeat():

>>> from itertools import repeat
>>> zip("abc", repeat(False))
[('a', False), ('b', False), ('c', False)]

Peter



More information about the Python-list mailing list