简体   繁体   中英

How do I use comprehension to make a list of values from a dictionary in python

{'AAPL': (175.96, 'Apple Inc'),
 'GOOGL': (0.00475, 'Alphabet Inc'),
 'TVIX': (0.0045, 'Credit Suisse AG')}

How I can extract a list of: Apple In , Alphabet Inc , and Credit Suisse AG

Use this list comprehension:

print([i[1] for i in yourdictionary.values()])

Output:

['Apple Inc', 'Alphabet Inc', 'Credit Suisse AG']

PS Change yourdictionary to the actual name of your dictionary.

l={'AAPL': (175.96, 'Apple Inc'), 'GOOGL': (0.00475, 'Alphabet Inc'),
'TVIX': (0.0045, 'Credit Suisse AG')} 
out=[]  
for k,v in l.items():
     make_list=list(v)
     out.append(make_list[1])
print(out)

I hope it work for you

Could also use tuple unpacking to select the second item from each tuple:

>>> d = {'AAPL': (175.96, 'Apple Inc'),
...  'GOOGL': (0.00475, 'Alphabet Inc'),
...  'TVIX': (0.0045, 'Credit Suisse AG')}
>>> [y for _, y in d.values()]
['Apple Inc', 'Alphabet Inc', 'Credit Suisse AG']

Or even a functional approach using operator.itemgetter() and map() :

>>> from operator import itemgetter
>>> list(map(itemgetter(1), d.values()))
['Apple Inc', 'Alphabet Inc', 'Credit Suisse AG']

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