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.!
You can use a list comprehension:
>>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
>>> [f['name'] for f in fields]
['count', 'type']
Take a look at list comprehensions
Maybe try:
names = [x['name'] for x in fields]
Example:
>>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
>>> [x['name'] for x in fields]
['count', 'type']
If names
already exists you can map (creating it in the same manner) to append each member of the new list you've created:
map(names.append, [x['name'] for x in fields])
Example:
>>> a = [1, 2 ,3]
>>> map(a.append, [2 ,3, 4])
[None, None, None]
>>> a
[1, 2, 3, 2, 3, 4]
Edit:
Not sure why I didn't mention list.extend
, but here is an example:
names.extend([x['name'] for x in fields])
or simply use the +
operator:
names += [x['name'] for x in fields]
you can also filter "on the fly" using an if
statement just like you'd expect:
names = [x['name'] for x in fields if x and x['name'][0] == 'a']
Example:
>>> l1 = ({'a':None}, None, {'a': 'aasd'})
>>> [x['a'] for x in l1 if (x and x['a'] and x['a'][0] == 'a')]
['aasd']
that will generate a list of all xs with names that start with 'a'
names = [x['name'] for x in fields]
would do.
and if the list names
already exists then:
names += [x['name'] for x in fields]
If the form is well defined, meaning, 'name' must be defined in each dict, then you may use:
map(lambda x: x['name'], fields)
else, you may use filter
before extracting, just to make sure you don't get KeyError
map(lambda x: x['name'], filter(lambda x: x.has_key('name'), fields))
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.