Combine two dictionaries into a list of 3-tuples

N

Nickolay Kolev

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
 
J

Jeff Epler

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)

iD8DBQFBkoRZJd01MZaTXX0RAvpNAJ4vYvie7kADHprwdOjuoa605/8eRwCeIBwX
vyDcQKHMKSgRsgB1Y/TtzAo=
=u8x/
-----END PGP SIGNATURE-----
 
N

Nickolay Kolev

Jeff said:
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
 
S

Scott David Daniels

Nickolay said:
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
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top