marktilbrook
marktilbrook

Reputation: 83

How to get dictionary value from key in a list?

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}

Upvotes: 2

Views: 77

Answers (4)

Abhinav Mathur
Abhinav Mathur

Reputation: 8111

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)

Upvotes: 1

Vikram Bhimbar
Vikram Bhimbar

Reputation: 31

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

this should help

Upvotes: 1

ygorg
ygorg

Reputation: 770

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.

Upvotes: 1

Abbas
Abbas

Reputation: 643

id_list = [d["id"] for d in dictlist ]

This should work for you

Upvotes: 1

Related Questions