What is a Pythonic way of doing the following transformation on a list of dicts?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
7
down vote

favorite












I have a list of dicts like this:



l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]


and I would like to obtain an output of this form:



>>> [('foo', 'bar'), ([1,2,3,4], [5,6,7,8])]


But short of for-looping and appending I don't see a solution. Is there a smarter way than doing this?



names = 
values =
for d in l:
names.append(d['name'])
values.append(d['values'])








share

















  • 2




    Keep in mind that your solution is probably the best there is performance-wise. All single-line comprehensions will probably need 2 full iterations over the list. Your code does it with one. Shorter code is not always the most Pythonic.
    – DeepSpace
    38 mins ago











  • I agree, I'm just curious whether this can be written in one line.
    – oarfish
    33 mins ago














up vote
7
down vote

favorite












I have a list of dicts like this:



l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]


and I would like to obtain an output of this form:



>>> [('foo', 'bar'), ([1,2,3,4], [5,6,7,8])]


But short of for-looping and appending I don't see a solution. Is there a smarter way than doing this?



names = 
values =
for d in l:
names.append(d['name'])
values.append(d['values'])








share

















  • 2




    Keep in mind that your solution is probably the best there is performance-wise. All single-line comprehensions will probably need 2 full iterations over the list. Your code does it with one. Shorter code is not always the most Pythonic.
    – DeepSpace
    38 mins ago











  • I agree, I'm just curious whether this can be written in one line.
    – oarfish
    33 mins ago












up vote
7
down vote

favorite









up vote
7
down vote

favorite











I have a list of dicts like this:



l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]


and I would like to obtain an output of this form:



>>> [('foo', 'bar'), ([1,2,3,4], [5,6,7,8])]


But short of for-looping and appending I don't see a solution. Is there a smarter way than doing this?



names = 
values =
for d in l:
names.append(d['name'])
values.append(d['values'])








share













I have a list of dicts like this:



l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]


and I would like to obtain an output of this form:



>>> [('foo', 'bar'), ([1,2,3,4], [5,6,7,8])]


But short of for-looping and appending I don't see a solution. Is there a smarter way than doing this?



names = 
values =
for d in l:
names.append(d['name'])
values.append(d['values'])






python python-3.x





share












share










share



share










asked 47 mins ago









oarfish

1,21721537




1,21721537







  • 2




    Keep in mind that your solution is probably the best there is performance-wise. All single-line comprehensions will probably need 2 full iterations over the list. Your code does it with one. Shorter code is not always the most Pythonic.
    – DeepSpace
    38 mins ago











  • I agree, I'm just curious whether this can be written in one line.
    – oarfish
    33 mins ago












  • 2




    Keep in mind that your solution is probably the best there is performance-wise. All single-line comprehensions will probably need 2 full iterations over the list. Your code does it with one. Shorter code is not always the most Pythonic.
    – DeepSpace
    38 mins ago











  • I agree, I'm just curious whether this can be written in one line.
    – oarfish
    33 mins ago







2




2




Keep in mind that your solution is probably the best there is performance-wise. All single-line comprehensions will probably need 2 full iterations over the list. Your code does it with one. Shorter code is not always the most Pythonic.
– DeepSpace
38 mins ago





Keep in mind that your solution is probably the best there is performance-wise. All single-line comprehensions will probably need 2 full iterations over the list. Your code does it with one. Shorter code is not always the most Pythonic.
– DeepSpace
38 mins ago













I agree, I'm just curious whether this can be written in one line.
– oarfish
33 mins ago




I agree, I'm just curious whether this can be written in one line.
– oarfish
33 mins ago












5 Answers
5






active

oldest

votes

















up vote
8
down vote













I would use a list comprehension (much like eyllanesc's) if I was writing this code for public consumption. But just for fun, here's a one-liner that doesn't use any fors.



>>> l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
>>> list(zip(*map(dict.values, l)))
[('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


(Note that this only reliably works if dictionaries preserve insertion order, which is not the case in all versions of Python. CPython 3.6 does it as an implementation detail, but it is only guaranteed behavior as of 3.7.)



Quick breakdown of the process:



  • dict.values returns a dict_values object, which is an iterable containing all the values of the dict.


  • map takes each dictionary in l and calls dict.values on it, returning an iterable of dict_values objects.


  • zip(*thing) is a classic "transposition" recipe, which takes an iterable-of-iterables and effectively flips it diagonally. E.g. [[a,b],[c,d]] becomes [[a,c], [b,d]]. This puts all the names into one tuple, and all the values into another.


  • list converts the zip object into a list.





share|improve this answer






















  • Nice! one-liner with a single iteration over the input list + a constant-length iteration.
    – DeepSpace
    32 mins ago











  • This was about what I had in mind, but I wouldn't want to rely on the order of dict items.
    – oarfish
    31 mins ago

















up vote
7
down vote













Use list comprehension:



l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
v = [tuple(k["name"] for k in l), tuple(k["values"] for k in l)]
print(v)


Output:



[('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]





share|improve this answer




















  • It may be worth noting that this solution (and quite possibly every one-liner) requires 2 iterations over the entire list (it may not be obvious at a quick glance)
    – DeepSpace
    36 mins ago







  • 4




    @DeepSpace I think that visible to the naked eye, there are 2 for loop. :-)
    – eyllanesc
    35 mins ago

















up vote
3
down vote













use map for this



names = tuple(map(lambda d: d['name'], l))
values = tuple(map(lambda d: d['values'], l))
result = [names, values]





share|improve this answer



























    up vote
    3
    down vote













    Not sure about performance, but here's another take using zip() and unpacking:



    list(zip(*[tuple(i.values()) for i in l]))

    # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


    Edit: As @DeepSpace pointed out, it can be further reduced down to:



    list(zip(*(i.values() for i in l)))


    Here's a longer, but more explicit answer if you want to define the orders yourself:



    list(zip(*(tuple(map(lambda k: i.get(k), ('name', 'values'))) for i in l)))

    # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]





    share|improve this answer






















    • Nice. This can be a little bit more memory friendly: list(zip(*(i.values() for i in l)))
      – DeepSpace
      30 mins ago







    • 1




      It seems that this does basically the same as @Kevin's solution with a listcomp instead of a map, correct?
      – oarfish
      30 mins ago










    • @DeepSpace Great point, I had the comprehension wrapped as a list before and it returned the dict_view so I forced it into a tuple. Nice catch! @oarfish, I just saw the other answer after I posted :( testing takes time. I do concede a zip/map combo is more compact.
      – Idlehands
      28 mins ago











    • @oarfish In response to your comment for Kevin's answer, I've updated my answer to include a variant where you can define an explicit order without relying on the dictionary's order (to make up for the fact that our answers are so similar).
      – Idlehands
      5 mins ago


















    up vote
    0
    down vote













    You can use operator.itemgetter to guarantee ordering of values:



    from operator import itemgetter

    fields = ('name', 'values')
    res = list(zip(*map(itemgetter(*fields), L)))

    print(res)

    [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


    If, assuming Python 3.6+, you cannot guarantee appropriate insertion-ordering of dictionaries within your input list, you will need to explicitly define an order as above.





    share




















      Your Answer





      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53046994%2fwhat-is-a-pythonic-way-of-doing-the-following-transformation-on-a-list-of-dicts%23new-answer', 'question_page');

      );

      Post as a guest






























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      8
      down vote













      I would use a list comprehension (much like eyllanesc's) if I was writing this code for public consumption. But just for fun, here's a one-liner that doesn't use any fors.



      >>> l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
      >>> list(zip(*map(dict.values, l)))
      [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


      (Note that this only reliably works if dictionaries preserve insertion order, which is not the case in all versions of Python. CPython 3.6 does it as an implementation detail, but it is only guaranteed behavior as of 3.7.)



      Quick breakdown of the process:



      • dict.values returns a dict_values object, which is an iterable containing all the values of the dict.


      • map takes each dictionary in l and calls dict.values on it, returning an iterable of dict_values objects.


      • zip(*thing) is a classic "transposition" recipe, which takes an iterable-of-iterables and effectively flips it diagonally. E.g. [[a,b],[c,d]] becomes [[a,c], [b,d]]. This puts all the names into one tuple, and all the values into another.


      • list converts the zip object into a list.





      share|improve this answer






















      • Nice! one-liner with a single iteration over the input list + a constant-length iteration.
        – DeepSpace
        32 mins ago











      • This was about what I had in mind, but I wouldn't want to rely on the order of dict items.
        – oarfish
        31 mins ago














      up vote
      8
      down vote













      I would use a list comprehension (much like eyllanesc's) if I was writing this code for public consumption. But just for fun, here's a one-liner that doesn't use any fors.



      >>> l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
      >>> list(zip(*map(dict.values, l)))
      [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


      (Note that this only reliably works if dictionaries preserve insertion order, which is not the case in all versions of Python. CPython 3.6 does it as an implementation detail, but it is only guaranteed behavior as of 3.7.)



      Quick breakdown of the process:



      • dict.values returns a dict_values object, which is an iterable containing all the values of the dict.


      • map takes each dictionary in l and calls dict.values on it, returning an iterable of dict_values objects.


      • zip(*thing) is a classic "transposition" recipe, which takes an iterable-of-iterables and effectively flips it diagonally. E.g. [[a,b],[c,d]] becomes [[a,c], [b,d]]. This puts all the names into one tuple, and all the values into another.


      • list converts the zip object into a list.





      share|improve this answer






















      • Nice! one-liner with a single iteration over the input list + a constant-length iteration.
        – DeepSpace
        32 mins ago











      • This was about what I had in mind, but I wouldn't want to rely on the order of dict items.
        – oarfish
        31 mins ago












      up vote
      8
      down vote










      up vote
      8
      down vote









      I would use a list comprehension (much like eyllanesc's) if I was writing this code for public consumption. But just for fun, here's a one-liner that doesn't use any fors.



      >>> l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
      >>> list(zip(*map(dict.values, l)))
      [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


      (Note that this only reliably works if dictionaries preserve insertion order, which is not the case in all versions of Python. CPython 3.6 does it as an implementation detail, but it is only guaranteed behavior as of 3.7.)



      Quick breakdown of the process:



      • dict.values returns a dict_values object, which is an iterable containing all the values of the dict.


      • map takes each dictionary in l and calls dict.values on it, returning an iterable of dict_values objects.


      • zip(*thing) is a classic "transposition" recipe, which takes an iterable-of-iterables and effectively flips it diagonally. E.g. [[a,b],[c,d]] becomes [[a,c], [b,d]]. This puts all the names into one tuple, and all the values into another.


      • list converts the zip object into a list.





      share|improve this answer














      I would use a list comprehension (much like eyllanesc's) if I was writing this code for public consumption. But just for fun, here's a one-liner that doesn't use any fors.



      >>> l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
      >>> list(zip(*map(dict.values, l)))
      [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


      (Note that this only reliably works if dictionaries preserve insertion order, which is not the case in all versions of Python. CPython 3.6 does it as an implementation detail, but it is only guaranteed behavior as of 3.7.)



      Quick breakdown of the process:



      • dict.values returns a dict_values object, which is an iterable containing all the values of the dict.


      • map takes each dictionary in l and calls dict.values on it, returning an iterable of dict_values objects.


      • zip(*thing) is a classic "transposition" recipe, which takes an iterable-of-iterables and effectively flips it diagonally. E.g. [[a,b],[c,d]] becomes [[a,c], [b,d]]. This puts all the names into one tuple, and all the values into another.


      • list converts the zip object into a list.






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 29 mins ago

























      answered 34 mins ago









      Kevin

      56.3k1165106




      56.3k1165106











      • Nice! one-liner with a single iteration over the input list + a constant-length iteration.
        – DeepSpace
        32 mins ago











      • This was about what I had in mind, but I wouldn't want to rely on the order of dict items.
        – oarfish
        31 mins ago
















      • Nice! one-liner with a single iteration over the input list + a constant-length iteration.
        – DeepSpace
        32 mins ago











      • This was about what I had in mind, but I wouldn't want to rely on the order of dict items.
        – oarfish
        31 mins ago















      Nice! one-liner with a single iteration over the input list + a constant-length iteration.
      – DeepSpace
      32 mins ago





      Nice! one-liner with a single iteration over the input list + a constant-length iteration.
      – DeepSpace
      32 mins ago













      This was about what I had in mind, but I wouldn't want to rely on the order of dict items.
      – oarfish
      31 mins ago




      This was about what I had in mind, but I wouldn't want to rely on the order of dict items.
      – oarfish
      31 mins ago












      up vote
      7
      down vote













      Use list comprehension:



      l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
      v = [tuple(k["name"] for k in l), tuple(k["values"] for k in l)]
      print(v)


      Output:



      [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]





      share|improve this answer




















      • It may be worth noting that this solution (and quite possibly every one-liner) requires 2 iterations over the entire list (it may not be obvious at a quick glance)
        – DeepSpace
        36 mins ago







      • 4




        @DeepSpace I think that visible to the naked eye, there are 2 for loop. :-)
        – eyllanesc
        35 mins ago














      up vote
      7
      down vote













      Use list comprehension:



      l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
      v = [tuple(k["name"] for k in l), tuple(k["values"] for k in l)]
      print(v)


      Output:



      [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]





      share|improve this answer




















      • It may be worth noting that this solution (and quite possibly every one-liner) requires 2 iterations over the entire list (it may not be obvious at a quick glance)
        – DeepSpace
        36 mins ago







      • 4




        @DeepSpace I think that visible to the naked eye, there are 2 for loop. :-)
        – eyllanesc
        35 mins ago












      up vote
      7
      down vote










      up vote
      7
      down vote









      Use list comprehension:



      l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
      v = [tuple(k["name"] for k in l), tuple(k["values"] for k in l)]
      print(v)


      Output:



      [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]





      share|improve this answer












      Use list comprehension:



      l = ['name': 'foo', 'values': [1,2,3,4], 'name': 'bar', 'values': [5,6,7,8]]
      v = [tuple(k["name"] for k in l), tuple(k["values"] for k in l)]
      print(v)


      Output:



      [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered 42 mins ago









      eyllanesc

      64.1k82751




      64.1k82751











      • It may be worth noting that this solution (and quite possibly every one-liner) requires 2 iterations over the entire list (it may not be obvious at a quick glance)
        – DeepSpace
        36 mins ago







      • 4




        @DeepSpace I think that visible to the naked eye, there are 2 for loop. :-)
        – eyllanesc
        35 mins ago
















      • It may be worth noting that this solution (and quite possibly every one-liner) requires 2 iterations over the entire list (it may not be obvious at a quick glance)
        – DeepSpace
        36 mins ago







      • 4




        @DeepSpace I think that visible to the naked eye, there are 2 for loop. :-)
        – eyllanesc
        35 mins ago















      It may be worth noting that this solution (and quite possibly every one-liner) requires 2 iterations over the entire list (it may not be obvious at a quick glance)
      – DeepSpace
      36 mins ago





      It may be worth noting that this solution (and quite possibly every one-liner) requires 2 iterations over the entire list (it may not be obvious at a quick glance)
      – DeepSpace
      36 mins ago





      4




      4




      @DeepSpace I think that visible to the naked eye, there are 2 for loop. :-)
      – eyllanesc
      35 mins ago




      @DeepSpace I think that visible to the naked eye, there are 2 for loop. :-)
      – eyllanesc
      35 mins ago










      up vote
      3
      down vote













      use map for this



      names = tuple(map(lambda d: d['name'], l))
      values = tuple(map(lambda d: d['values'], l))
      result = [names, values]





      share|improve this answer
























        up vote
        3
        down vote













        use map for this



        names = tuple(map(lambda d: d['name'], l))
        values = tuple(map(lambda d: d['values'], l))
        result = [names, values]





        share|improve this answer






















          up vote
          3
          down vote










          up vote
          3
          down vote









          use map for this



          names = tuple(map(lambda d: d['name'], l))
          values = tuple(map(lambda d: d['values'], l))
          result = [names, values]





          share|improve this answer












          use map for this



          names = tuple(map(lambda d: d['name'], l))
          values = tuple(map(lambda d: d['values'], l))
          result = [names, values]






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 42 mins ago









          user3142459

          352111




          352111




















              up vote
              3
              down vote













              Not sure about performance, but here's another take using zip() and unpacking:



              list(zip(*[tuple(i.values()) for i in l]))

              # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


              Edit: As @DeepSpace pointed out, it can be further reduced down to:



              list(zip(*(i.values() for i in l)))


              Here's a longer, but more explicit answer if you want to define the orders yourself:



              list(zip(*(tuple(map(lambda k: i.get(k), ('name', 'values'))) for i in l)))

              # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]





              share|improve this answer






















              • Nice. This can be a little bit more memory friendly: list(zip(*(i.values() for i in l)))
                – DeepSpace
                30 mins ago







              • 1




                It seems that this does basically the same as @Kevin's solution with a listcomp instead of a map, correct?
                – oarfish
                30 mins ago










              • @DeepSpace Great point, I had the comprehension wrapped as a list before and it returned the dict_view so I forced it into a tuple. Nice catch! @oarfish, I just saw the other answer after I posted :( testing takes time. I do concede a zip/map combo is more compact.
                – Idlehands
                28 mins ago











              • @oarfish In response to your comment for Kevin's answer, I've updated my answer to include a variant where you can define an explicit order without relying on the dictionary's order (to make up for the fact that our answers are so similar).
                – Idlehands
                5 mins ago















              up vote
              3
              down vote













              Not sure about performance, but here's another take using zip() and unpacking:



              list(zip(*[tuple(i.values()) for i in l]))

              # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


              Edit: As @DeepSpace pointed out, it can be further reduced down to:



              list(zip(*(i.values() for i in l)))


              Here's a longer, but more explicit answer if you want to define the orders yourself:



              list(zip(*(tuple(map(lambda k: i.get(k), ('name', 'values'))) for i in l)))

              # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]





              share|improve this answer






















              • Nice. This can be a little bit more memory friendly: list(zip(*(i.values() for i in l)))
                – DeepSpace
                30 mins ago







              • 1




                It seems that this does basically the same as @Kevin's solution with a listcomp instead of a map, correct?
                – oarfish
                30 mins ago










              • @DeepSpace Great point, I had the comprehension wrapped as a list before and it returned the dict_view so I forced it into a tuple. Nice catch! @oarfish, I just saw the other answer after I posted :( testing takes time. I do concede a zip/map combo is more compact.
                – Idlehands
                28 mins ago











              • @oarfish In response to your comment for Kevin's answer, I've updated my answer to include a variant where you can define an explicit order without relying on the dictionary's order (to make up for the fact that our answers are so similar).
                – Idlehands
                5 mins ago













              up vote
              3
              down vote










              up vote
              3
              down vote









              Not sure about performance, but here's another take using zip() and unpacking:



              list(zip(*[tuple(i.values()) for i in l]))

              # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


              Edit: As @DeepSpace pointed out, it can be further reduced down to:



              list(zip(*(i.values() for i in l)))


              Here's a longer, but more explicit answer if you want to define the orders yourself:



              list(zip(*(tuple(map(lambda k: i.get(k), ('name', 'values'))) for i in l)))

              # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]





              share|improve this answer














              Not sure about performance, but here's another take using zip() and unpacking:



              list(zip(*[tuple(i.values()) for i in l]))

              # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


              Edit: As @DeepSpace pointed out, it can be further reduced down to:



              list(zip(*(i.values() for i in l)))


              Here's a longer, but more explicit answer if you want to define the orders yourself:



              list(zip(*(tuple(map(lambda k: i.get(k), ('name', 'values'))) for i in l)))

              # [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 7 mins ago

























              answered 31 mins ago









              Idlehands

              2,5981316




              2,5981316











              • Nice. This can be a little bit more memory friendly: list(zip(*(i.values() for i in l)))
                – DeepSpace
                30 mins ago







              • 1




                It seems that this does basically the same as @Kevin's solution with a listcomp instead of a map, correct?
                – oarfish
                30 mins ago










              • @DeepSpace Great point, I had the comprehension wrapped as a list before and it returned the dict_view so I forced it into a tuple. Nice catch! @oarfish, I just saw the other answer after I posted :( testing takes time. I do concede a zip/map combo is more compact.
                – Idlehands
                28 mins ago











              • @oarfish In response to your comment for Kevin's answer, I've updated my answer to include a variant where you can define an explicit order without relying on the dictionary's order (to make up for the fact that our answers are so similar).
                – Idlehands
                5 mins ago

















              • Nice. This can be a little bit more memory friendly: list(zip(*(i.values() for i in l)))
                – DeepSpace
                30 mins ago







              • 1




                It seems that this does basically the same as @Kevin's solution with a listcomp instead of a map, correct?
                – oarfish
                30 mins ago










              • @DeepSpace Great point, I had the comprehension wrapped as a list before and it returned the dict_view so I forced it into a tuple. Nice catch! @oarfish, I just saw the other answer after I posted :( testing takes time. I do concede a zip/map combo is more compact.
                – Idlehands
                28 mins ago











              • @oarfish In response to your comment for Kevin's answer, I've updated my answer to include a variant where you can define an explicit order without relying on the dictionary's order (to make up for the fact that our answers are so similar).
                – Idlehands
                5 mins ago
















              Nice. This can be a little bit more memory friendly: list(zip(*(i.values() for i in l)))
              – DeepSpace
              30 mins ago





              Nice. This can be a little bit more memory friendly: list(zip(*(i.values() for i in l)))
              – DeepSpace
              30 mins ago





              1




              1




              It seems that this does basically the same as @Kevin's solution with a listcomp instead of a map, correct?
              – oarfish
              30 mins ago




              It seems that this does basically the same as @Kevin's solution with a listcomp instead of a map, correct?
              – oarfish
              30 mins ago












              @DeepSpace Great point, I had the comprehension wrapped as a list before and it returned the dict_view so I forced it into a tuple. Nice catch! @oarfish, I just saw the other answer after I posted :( testing takes time. I do concede a zip/map combo is more compact.
              – Idlehands
              28 mins ago





              @DeepSpace Great point, I had the comprehension wrapped as a list before and it returned the dict_view so I forced it into a tuple. Nice catch! @oarfish, I just saw the other answer after I posted :( testing takes time. I do concede a zip/map combo is more compact.
              – Idlehands
              28 mins ago













              @oarfish In response to your comment for Kevin's answer, I've updated my answer to include a variant where you can define an explicit order without relying on the dictionary's order (to make up for the fact that our answers are so similar).
              – Idlehands
              5 mins ago





              @oarfish In response to your comment for Kevin's answer, I've updated my answer to include a variant where you can define an explicit order without relying on the dictionary's order (to make up for the fact that our answers are so similar).
              – Idlehands
              5 mins ago











              up vote
              0
              down vote













              You can use operator.itemgetter to guarantee ordering of values:



              from operator import itemgetter

              fields = ('name', 'values')
              res = list(zip(*map(itemgetter(*fields), L)))

              print(res)

              [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


              If, assuming Python 3.6+, you cannot guarantee appropriate insertion-ordering of dictionaries within your input list, you will need to explicitly define an order as above.





              share
























                up vote
                0
                down vote













                You can use operator.itemgetter to guarantee ordering of values:



                from operator import itemgetter

                fields = ('name', 'values')
                res = list(zip(*map(itemgetter(*fields), L)))

                print(res)

                [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


                If, assuming Python 3.6+, you cannot guarantee appropriate insertion-ordering of dictionaries within your input list, you will need to explicitly define an order as above.





                share






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  You can use operator.itemgetter to guarantee ordering of values:



                  from operator import itemgetter

                  fields = ('name', 'values')
                  res = list(zip(*map(itemgetter(*fields), L)))

                  print(res)

                  [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


                  If, assuming Python 3.6+, you cannot guarantee appropriate insertion-ordering of dictionaries within your input list, you will need to explicitly define an order as above.





                  share












                  You can use operator.itemgetter to guarantee ordering of values:



                  from operator import itemgetter

                  fields = ('name', 'values')
                  res = list(zip(*map(itemgetter(*fields), L)))

                  print(res)

                  [('foo', 'bar'), ([1, 2, 3, 4], [5, 6, 7, 8])]


                  If, assuming Python 3.6+, you cannot guarantee appropriate insertion-ordering of dictionaries within your input list, you will need to explicitly define an order as above.






                  share











                  share


                  share










                  answered 3 mins ago









                  jpp

                  76.1k184390




                  76.1k184390



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53046994%2fwhat-is-a-pythonic-way-of-doing-the-following-transformation-on-a-list-of-dicts%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Comments

                      Popular posts from this blog

                      What does second last employer means? [closed]

                      List of Gilmore Girls characters

                      One-line joke