views:

136

answers:

3

Him

I have a dictionary dict1['a'] = [ [1,2], [3,4] ]. I need to generate a list out of this dictionary as l1 = [2, 4] i.e., a list out of the second element of each inner list. It can be a separate list or even the dictionary can be modified as dict1['a'] = [2,4]. Any idea would be appreciated.

+7  A: 

Given a list:

>>> lst = [ [1,2], [3,4] ]

You can extract the second element of each sublist with a simple list comprehension:

>>> [x[1] for x in lst]
[2, 4]

If you want to do this for every value in a dictionary, you can iterate over the dictionary. I'm not sure exactly what you want your final data to look like, but something like this may help:

>>> dict1 = {}
>>> dict1['a'] = [ [1,2], [3,4] ]
>>> [(k, [x[1] for x in v]) for k, v in dict1.items()]   
[('a', [2, 4])]

dict.items() returns (key, value) pairs from the dictionary, as a list. So this code will extract each key in your dictionary and pair it with a list generated as above.

John Fouhy
And in Python 3, could do this in a dict comprehension, too, if a dictionary result should be preferred - looks like: {k: [x[1] for x in v] for k,v in dict1.items()}
Anon
A: 

a list out of the second element of each inner list

that sounds like [sl[1] for sl in dict1['a']] -- so what's the QUESTION?!-)

Alex Martelli
+1  A: 

Assuming that each value in the dictionary is a list of pairs, then this should do it for you:

[pair[1] for pairlist in dict1.values() for pair in pairlist]

As you can see:

  • dict1.values() gets you just the values in your dict,
  • for pairlist in dict1.values() gets you all the lists of pairs,
  • for pair in pairlist gets you all the pairs in each of those lists,
  • and pair[1] gets you the second value in each pair.

Try it out. The Python shell is your friend!...

>>> dict1 = {}
>>> dict1['a'] = [[1,2], [3,4]]
>>> dict1['b'] = [[5, 6], [42, 69], [220, 284]]
>>> 
>>> dict1.values()
[[[1, 2], [3, 4]], [[5, 6], [42, 69], [220, 284]]]
>>> 
>>> [pairlist for pairlist in dict1.values()]
[[[1, 2], [3, 4]], [[5, 6], [42, 69], [220, 284]]]
>>> # No real difference here, but we can refer to each list now.
>>> 
>>> [pair for pairlist in dict1.values() for pair in pairlist]
[[1, 2], [3, 4], [5, 6], [42, 69], [220, 284]]
>>> 
>>> # Finally...
>>> [pair[1] for pairlist in dict1.values() for pair in pairlist]
[2, 4, 6, 69, 284]

While I'm at it, I'll just say: ipython loves you!

eksortso