简体   繁体   中英

Possible to extract a List from a Dictionary of Lists in Python?

I understand that using .values() will pull the values out of the dictionary into a list, but im curious if it is possible to pull the second item (for instance) out of the lists in a dictionary without a loop.

for example:

dictionary1={
             fish : [1, 2, 3],
             dog :  [9, 5, 8],
             cat :  [4, 4, 4]
             }

I would like to extract the list:

[3, 8, 4]

Just curious if there is a cleaner way than looping, Thanks!

This should do it:

>>> [v[2] for v in dictionary1.values()]
[3, 8, 4]

You should be putting the keys in single/double quotes in dictionary.Try this.

d1 = {
             "fish" : [1, 2, 3],
             "dog" :  [9, 5, 8],
             "cat" :  [4, 4, 4]
             }
print [x[-1] for x in d1.values()]

In your question (if I am correct), you are basically creating a 2D array from dictionary values and then trying to get a particular column of that 2D array. If so you can easily do that using a python package numpy , documentation of the package is available here ,

I think following code will help you get started,

import numpy

dictionary1=dict(
             fish = [1, 2, 3],
             dog =  [9, 5, 8],
             cat =  [4, 4, 4]
             )

numpy_array = numpy.array(dictionary1.values())
column_number = 2

print numpy_array[:,column_number]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM