Building a dictionary from a tuple of variable length

B

bg_ie

Hi,

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?

Thanks for your help,

Barry.
 
M

Marc 'BlackJack' Rintsch

Therefore, how do I build the tuple of Falses to reflect the length of
my t tuple?

In [1]: dict.fromkeys(('one', 'two', 'three'), False)
Out[1]: {'three': False, 'two': False, 'one': False}

Ciao,
Marc 'BlackJack' Rintsch
 
P

Peter Otten

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:
{'three': False, 'two': False, 'one': False}

When you are just interested in the list of tuples, use repeat():
[('a', False), ('b', False), ('c', False)]

Peter
 
J

Jussi Salmela

(e-mail address removed) kirjoitti:
Hi,

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?

Thanks for your help,

Barry.

Another variation:

d = dict((x, False) for x in t)

Cheers,
Jussi
 
P

Pierre Quentel

Hi,
Therefore, how do I build the tuple of Falses to reflect the length of my t tuple?

Yet another solution :

d = dict(zip(t,[False]*len(t)))

Pierre
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,692
Latest member
JenniferTi

Latest Threads

Top