Dictionary to tuple

John Roth newsgroups at jhrothjr.com
Tue Jun 28 20:13:18 CEST 2005

"bruno modulix" <onurb at xiludom.gro> wrote in message 
news:42c16464$0$26260$626a14ce at news.free.fr...
> Odd-R. wrote:
>> I have a dictionary, and I want to convert it to a tuple,
>> that is, I want each key - value pair in the dictionary
>> to be a tuple in a tuple.
>> If this is the dictionary {1:'one',2:'two',3:'three'},
>> then I want this to be the resulting tuple:
>> ((1,'one'),(2,'two'),(3,'three')).
>> I have been trying for quite some time now, but I do not
>> get the result as I want it. Can this be done, or is it not
>> possible?
> It's of course possible, and even a no-brainer:
> dic = {1:'one',2:'two',3:'three'}
> tup = tuple(dic.items())

I think I'll add a little clarification since the OP is really new
to Python. The (dict.items()) part of the expression returns a
list, and if you want to sort it, then you need to sort the list
and then convert it to a tuple.

dic = {1:'one',2:'two',3:'three'}
tup = tuple(dic)

This points up the fact that the final conversion to a tuple
may not be necessary. Whether or not is is depends on
the circumstances.

>> I must also add that I'm new to Python.
> Welcome on board.

John Roth

> -- 
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in 'onurb at xiludom.gro'.split('@')])" 

More information about the Python-list mailing list