Creating a list from a complex dictionary

I have a dictionary dict1['a'] = [ [1,2], [3,4] ]

and need to create a list from it like l1 = [2, 4]

. That is, a list from the second element of each inner list. It can be a separate list or even a dictionary can be changed like dict1['a'] = [2,4]

.

+2


source to share


3 answers


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

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

      

As you can see:

  • dict1.values()

    only gets the values ​​in your dict,
  • for pairlist in dict1.values()

    gets all lists of pairs,
  • for pair in pairlist

    gets all pairs in each of these lists,
  • and pair[1]

    gets the second value in each pair.


Try it. 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!

+2


source


Given the list:

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

      

You can extract the second element of each sublist by simply understanding the list:

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

      



If you want to do this for every value in the dictionary, you can iterate over the dictionary. I'm not sure what you want your final data to look like, but something like this might 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 a dictionary as a list. So this code will extract every key in your dictionary and link it to the list generated as above.

+8


source


a list of the second element each inner list

which sounds like [sl[1] for sl in dict1['a']]

- so the QUESTION ?! -)

0


source







All Articles