I have a list of fields in this form
fields = [{\'name\':\'count\', \'label\':\'Count\'},{\'name\':\'type\', \'label\':\'Type\'}]
I\'d like
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))
You can use a list comprehension:
>>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
>>> [f['name'] for f in fields]
['count', 'type']
names = [x['name'] for x in fields]
would do.
and if the list names
already exists then:
names += [x['name'] for x in fields]
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 x-s with names that start with 'a'