Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert list of dicts to list

I have a list of fields in this form

fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]

I'd like to extract just the names and put it in a list. Currently, I'm doing this:

names = [] 
for field in fields:
    names.append(field['name'])

Is there another way to do the same thing, that doesn't involve looping through the list.

I'm using python 2.7.

Thanks for your help.!

like image 648
Haleemur Ali Avatar asked Jan 02 '14 20:01

Haleemur Ali


People also ask

How do I turn a dict into a list?

Python convert dict to list of pairs. In Python, a dictionary provides method items() which returns an iterable sequence of all elements from the dictionary. The items() method basically converts a dictionary to a list along with that we can also use the list() function to get a list of tuples/pairs.

How do I convert a list of dictionaries in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do I convert a list to a dictionary in Python w3schools?

The zip() function is an in-built function that takes iterators (can be zero or more), aggregates and combines them, and returns them as an iterator of tuples and the dict() function creates a new dictionary.

How do you convert a list to a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


1 Answers

You can use a list comprehension:

>>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
>>> [f['name'] for f in fields]
['count', 'type']
like image 91
Hyperboreus Avatar answered Oct 11 '22 17:10

Hyperboreus