473,560 Members | 2,935 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 19185
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.iterite ms())
d = {1: 'one', 2: 'two', 3: 'three'}
tuple(d.iterite ms())

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

iD8DBQFCwWVSJd0 1MZaTXX0RAiFwAK ChDHQYL/lUx6HEHJsbvqq9n SXI/gCfTvT2
CdRYwJqNJH0Emnm 86MMavms=
=LyEz
-----END PGP SIGNATURE-----

Jul 19 '05 #3
On 28 Jun 2005 14:45:19 GMT, Odd-R. <od**@home.no.n o> 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.iterite ms())


--
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
1367
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
3656
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, I'm just curious why it is neccesary.. Thanks,
15
2962
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
10734
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 future Python versions and let dict.keys() and dict.values() both return sets instead of lists. If d is a dict, code like: for x in d.keys():
4
1504
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 tokens you're looking for). In another case I have a function that handles a different set of tokens and so it can't use the same arguments as the...
4
2245
by: laxmikiran.bachu | last post by:
Can we have change a unicode string Type object to a Tuple type object.. If so how ????
16
28708
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
2654
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, this seems like something one would want to change - why raise an error *and* execute the thing it was complaining about? The discussion seems to have...
10
1479
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 function then: .... fundict = newfun ....
0
7635
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8068
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5176
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3589
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1171
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
882
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.