convert list of dicts to list

后端 未结 4 2024
有刺的猬
有刺的猬 2020-12-16 19:07

I have a list of fields in this form

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

I\'d like

相关标签:
4条回答
  • 2020-12-16 19:40

    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))
    
    0 讨论(0)
  • 2020-12-16 19:48

    You can use a list comprehension:

    >>> fields = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}]
    >>> [f['name'] for f in fields]
    ['count', 'type']
    
    0 讨论(0)
  • 2020-12-16 20:01

    names = [x['name'] for x in fields] would do.

    and if the list names already exists then:

    names += [x['name'] for x in fields]
    
    0 讨论(0)
  • 2020-12-16 20:06

    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'

    0 讨论(0)
提交回复
热议问题