How to get dictionary value from key in a list?

Viewed 67

I am trying to create a new list from a list of dictionary items. Below is an example of 1 dictionary item.

{'id': 'bitcoin',
  'symbol': 'btc',
  'name': 'Bitcoin',
  'current_price': 11907.43,
  'market_cap': 220817187069,
  'market_cap_rank': 1}

I want the list to just be of the id item. So what I am trying to achieve is a list with items {'bitcoin', 'etc', 'etc}

4 Answers
list = [ i['id'] for i in list_of_dict]

this should help

Simple and readable code that solves the purpose:

main_list = []
for item in main_dict:
    main_list.append(item.get("id", None))
print(main_list)
id_list = [d["id"] for d in dictlist ]

This should work for you

You can use list comprehension:

my_list = [{'id': 'bitcoin', 'symbol': 'btc', ...}, ...]
[d['id'] for d in my_list]

Which translates to : for each dictionary in my_list, extract the 'id' key.

Related