Inverse of dict(zip(x,y))

A

Andre Engels

I usually get properties that I compute, in a dictionary like property
= [key1: val1, key2:val2, ...] and then I usually want to plot them in
pylab, which AFAIK requires x and y as lists for the plot argument.
Then I need to get the lists [key1, key2, ...] and [val1, val2, ...].
And now I wonder if there a more efficient way doing what I described
above!! ;)

If the dict = {key1: val1, key2: val2, ...}, you can do:

for key in dict:
plot(key,dictionary[key])
 
A

Andre Engels

If the dict = {key1: val1, key2: val2, ...}, you can do:

for key in dict:
   plot(key,dictionary[key])

Of course I meant:

for key in dict:
plot(key,dict[key])
 
C

Carl Banks

Piet said:
Can someone suggest a easy method to do the inverse of dict(zip(x,y))
to get two lists x and y?
So, if x and y are two lists, it is easier to make a dictionary using
d = dict(zip(x,y)), but if I have d of the form, d = {x1:y1,
x2:y2, ...}, what is there any trick to get lists x = [x1, x2, ...]
and y = [y1, y2, ...]
AE> x = d.keys()
AE> y = [d[e] for d in x]
AE> y = d.values() might also work, but I am not sure whether d.keys() and
AE> d.values() are guaranteed to use the same order.
Yes, they are if the dictionary is not changed in the meantime (not even
inserting and removing the same thing). See the library documentation,
section dict.

Still I'd like to see an application where this really matters (that
keys() and values() match in order)


Just as an example, if you are using a third-party library function
that demands side-by-side inputs in respective lists, you could make
use of it. That's not a good interface, IMHO, but if you have to use
such a library, and you want to supply key-value pairs, then you can
use keys and values seperately.

populate_database(d.keys(),d.values())



Carl Banks
 

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
474,294
Messages
2,571,511
Members
48,213
Latest member
DonnellTol

Latest Threads

Top