469,328 Members | 1,247 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,328 developers. It's quick & easy.

Combine two dictionaries into a list of 3-tuples

Hi all,

Continuing the search for interesting challenges with lists, tuples and
dictionaries I am looking for a way to do the following.

one = {
'a' : 1,
'b' : 2,
'c' : 3
}

two = {
'a' : [4,5,6],
'b' : [8,9,10],
'c' : [11,12,13]
}

The goal is

[('a', 1, [4,5,6]), ('b', 2, [8,9,10]), ('c', 3, [11,12,13])]
My attempts so far:

[(t, c, l) for t, c in one.items() if (t, l) in two.items()]

gives me a 'l is not defined'

---------------

[(t, c, l) for t, c in one.items() for (t, l) in two.items()]

gives me a lot more than I need :-)

---------------

Many thanks in advance!

Cheers,
-- Nickolay
Jul 18 '05 #1
3 1744
How about
[(k, v, two[v]) for k, v in one.items()]
or
[(k, v, two[v]) for k, v in one.items() if k in two]
or
[(k, v, two.get(v, None)) for k, v in one.items()]
depending on what you want to do when a key doesn't exist in "two"

Jeff

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

iD8DBQFBkoRZJd01MZaTXX0RAvpNAJ4vYvie7kADHprwdOjuoa 605/8eRwCeIBwX
vyDcQKHMKSgRsgB1Y/TtzAo=
=u8x/
-----END PGP SIGNATURE-----

Jul 18 '05 #2
Jeff Epler wrote:
How about
[(k, v, two[v]) for k, v in one.items()]
or
[(k, v, two[v]) for k, v in one.items() if k in two]
or
[(k, v, two.get(v, None)) for k, v in one.items()]
depending on what you want to do when a key doesn't exist in "two"

Jeff


I should have thought of that, it is sooo simple... :-)

Thanks again.

Cheers,
-- Nickolay
Jul 18 '05 #3
Nickolay Kolev wrote:
My attempts so far:
... [(t, c, l) for t, c in one.items() for (t, l) in two.items()]


Simply forget about items for two.
[(key, val1, two[key]) for key, val1 in one.items() if key in two]

--Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Narendra C. Tulpule | last post: by
7 posts views Thread by Kerry Neilson | last post: by
8 posts views Thread by Frohnhofer, James | last post: by
10 posts views Thread by Bulba! | last post: by
210 posts views Thread by Christoph Zwerschke | last post: by
2 posts views Thread by David Pratt | last post: by
5 posts views Thread by Ladislav Andel | last post: by
9 posts views Thread by Abandoned | last post: by
1 post views Thread by Edwin.Madari | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by Purva khokhar | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.