Dictionary to tuple

bruno modulix onurb at xiludom.gro
Tue Jun 28 10:53:22 EDT 2005


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())

The bad news is that dict are *not* ordered, so you'll have to sort the
result yourself if needed :(

The good news is that sorting a sequence is a no-brainer too !-)

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

-- 
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