473,325 Members | 2,816 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Dictionary to tuple

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?
I must also add that I'm new to Python.

Thanks in advance.

--
Har du et kjøleskap, har du en TV
så har du alt du trenger for å leve

-Jokke & Valentinerne
Jul 19 '05 #1
9 19148
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 'o****@xiludom.gro'.split('@')])"
Jul 19 '05 #2
It looks like you want tuple(d.iteritems())
d = {1: 'one', 2: 'two', 3: 'three'}
tuple(d.iteritems())

((1, 'one'), (2, 'two'), (3, 'three'))

You could also use tuple(d.items()). The result is essentially the
same. Only if the dictionary is extremely large does the difference
matter. (or if you're using an older version of Python without the
iteritems method)

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFCwWVSJd01MZaTXX0RAiFwAKChDHQYL/lUx6HEHJsbvqq9nSXI/gCfTvT2
CdRYwJqNJH0Emnm86MMavms=
=LyEz
-----END PGP SIGNATURE-----

Jul 19 '05 #3
On 28 Jun 2005 14:45:19 GMT, Odd-R. <od**@home.no.no> 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')).
d = {1:'one',2:'two',3:'three'}
t = tuple([(k,v) for k,v in d.iteritems()])
t ((1, 'one'), (2, 'two'), (3, 'three'))

Jul 19 '05 #4
Tim Williams (gmail) wrote:
(snip)
d = {1:'one',2:'two',3:'three'}
t = tuple([(k,v) for k,v in d.iteritems()])


Err... don't you spot any useless code here ?-)

(tip: dict.items() already returns a list of (k,v) tuples...)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 19 '05 #5
bruno modulix wrote:
Err... don't you spot any useless code here ?-)

(tip: dict.items() already returns a list of (k,v) tuples...)


But it doesn't return a tuple of them. Which is what the tuple call
there does.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
But when I reached the finished line / Young black male
-- Ice Cube
Jul 19 '05 #6
Erik Max Francis wrote:
bruno modulix wrote:
Err... don't you spot any useless code here ?-)

(tip: dict.items() already returns a list of (k,v) tuples...)


But it doesn't return a tuple of them. Which is what the tuple call
there does.


The useless code referred to was the list comprehension.
t = tuple([(k,v) for k,v in d.iteritems()])
versus
t = tuple(d.items())
or even
t = tuple(d.iteritems())


--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Jul 19 '05 #7
Erik Max Francis wrote:
But it doesn't return a tuple of them. Which is what the tuple call
there does.


Yes, but I think he meant:

t = tuple(d.items())

--
Jeremy Sanders
http://www.jeremysanders.net/
Jul 19 '05 #8
"bruno modulix" <on***@xiludom.gro> wrote in message
news:42***********************@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'}
dic.sort()
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 'on***@xiludom.gro'.split('@')])"


Jul 19 '05 #9
Erik Max Francis wrote:
bruno modulix wrote:
Err... don't you spot any useless code here ?-)

(tip: dict.items() already returns a list of (k,v) tuples...)


But it doesn't return a tuple of them. Which is what the tuple call
there does.


Of course, but the list-to-tuple conversion is not the point here. The
useless part might be more obvious in this snippet:

my_list = [(1, 'one'), (2, 'two'), (3, 'three')]
my_tup = tuple([(k, v) for k, v in my_list])
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Jinming Xu | last post by:
Sorry for the previous message. It's really a simple question and I have solved it myself. Thanks, Jinming ------------------------------------------------------------------------ Hi Folks,
50
by: Will McGugan | last post by:
Hi, Why is that a tuple doesnt have the methods 'count' and 'index'? It seems they could be present on a immutable object. I realise its easy enough to convert the tuple to a list and do this,...
15
by: Stefan Behnel | last post by:
Hi! I'm trying to do this in Py2.4b1: ------------------------------- import logging values = {'test':'bla'} logging.log(logging.FATAL, 'Test is %(test)s', values)...
90
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
4
by: 63q2o4i02 | last post by:
Hi, I'm writing a hand-written recursive decent parser for SPICE syntax parsing. In one case I have one function that handles a bunch of similar cases (you pass the name and the number of...
4
by: laxmikiran.bachu | last post by:
Can we have change a unicode string Type object to a Tuple type object.. If so how ????
16
by: Davy | last post by:
Hi all, We know that list cannot be used as key of dictionary. So, how to work around it? For example, there is random list like l=. Any suggestions are welcome! Best regards,
11
by: montyphyton | last post by:
Recently, I got into a debate on programming.reddit.com about what should happen in the following case: Currently, Python raises an error *and* changes the first element of the tuple. Now,...
10
by: mk | last post by:
Calvin Spealman wrote: Well, basically nothing except I need to remember I have to do that. Suppose one does that frequently in a program. It becomes tedious. I think I will define some helper...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.