0

I need help converting these dictionaries to a single dictionary. See below

data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]

I want to convert it to below:

{'x':[3,5,1], 'y':[3,3,4]

thank you!

Xantium
  • 11,201
  • 10
  • 62
  • 89
Jen
  • 1
  • @cᴏʟᴅsᴘᴇᴇᴅ I think [this](https://stackoverflow.com/questions/5946236/how-to-merge-multiple-dicts-with-same-key) is a more accurate dupe, mind if I change it? – Aran-Fey May 05 '18 at 22:29
  • @Aran-Fey Yes sir, please do. – cs95 May 05 '18 at 22:30

2 Answers2

1

You can use a dictionary comprehension:

data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
new_data = {i:[c.get(i) for c in data] for i in ['x', 'y']}

Output:

{'y': [3, 3, 4], 'x': [3, 5, 1]}

However, to be more generic, you can use reduce:

from functools import reduce
new_result = {
    i : [c.get(i) for c in data] 
    for i in set(reduce(
      lambda x, y:list(getattr(x, 'keys', lambda :x)()) + list(y.keys()), data)
   )
} 

Edit: shorter generic solution:

new_s = {i for b in map(dict.keys, data) for i in b}
new_data = {i:[c.get(i) for c in data] for i in new_s}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • 1
    Good answer, upvoted. – cs95 May 05 '18 at 22:29
  • I would iterate over `data.keys()` instead of `[x, y]` for a generic solution. – cs95 May 05 '18 at 22:29
  • @cᴏʟᴅsᴘᴇᴇᴅ Good point. I just added another generic possibility, but I will add yours with plain `dict.keys` as well. – Ajax1234 May 05 '18 at 22:30
  • Not a fan of the reduce solution. ;-/ However, if you're going to insist on one-liners, you should strive to at least obey PEP-8. For example, you can always break it into multiple lines for readability. :) – cs95 May 05 '18 at 22:32
  • No, not like that. See [here](http://dpaste.com/214EAVH). – cs95 May 05 '18 at 22:34
  • Last nitpick: PEP-8 recommends 4 spaces for indent (not 2). Keep it up, and you'll be seeing a lot more +10s from me ;-) – cs95 May 05 '18 at 22:36
  • @Aran-Fey fixed. Please see my recent edit. – Ajax1234 May 05 '18 at 22:47
1

Here is an easy way to do it:

data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]


emptyX = []
emptyY = []

for i in data:
    emptyX.append(i['x'])
    emptyY.append(i['y'])

final = {'x':emptyX, 'y':emptyY}

print(final)

Here you just create two empty lists. One to store the x values and one to store the y values and then add the value of each dictionary while the forloop initerates through the list.

Xantium
  • 11,201
  • 10
  • 62
  • 89