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.!
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.
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.
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.
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.
You can use a list comprehension:
>>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
>>> [f['name'] for f in fields]
['count', 'type']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With