JoshG
JoshG

Reputation: 6735

Mapping Python list values to dictionary values

I have a list of rows...

rows = [2, 21]

And a dictionary of data...

data = {'x': [46, 35], 'y': [20, 30]}

I'd like to construct a second dictionary, dataRows, keyed by the row that looks like this...

dataRows = {2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}

I tried the following code, but the values of dataRows are always the same (last value in loop):

for i, row in enumerate(rows):
    for key, value in data.items():
        dataRows[row] = value[i]

Any assistance would be greatly appreciated.

Upvotes: 2

Views: 425

Answers (4)

Sven Marnach
Sven Marnach

Reputation: 601639

Here's a Python 3 solution with only one explicit loop:

{r: dict(zip(data.keys(), d)) for r, *d in zip(rows, *data.values())}

Upvotes: 0

seokhoonlee
seokhoonlee

Reputation: 1038

Following code works for me:

rows = [2, 21]

data = {'x': [46, 35], 'y': [20, 30]}

dataRows = {}

for i, row in enumerate(rows):
  dataRows[row] = {}
  dataRows[row]['x'] = data['x'][i]
  dataRows[row]['y'] = data['y'][i]

print dataRows

UPDATE:

You can also use collections.defaultdict() to avoid assigning dict to dataRows in every iteration.

import collections

rows = [2, 21]

data = {'x': [46, 35], 'y': [20, 30]}

dataRows = collections.defaultdict(dict)

for i, row in enumerate(rows):
  for key, value in data.items():
    dataRows[row][key] = value[i]

print dataRows

Upvotes: 2

donkopotamus
donkopotamus

Reputation: 23176

In a line:

>>> {r: {k: v[i] for k, v in data.items()} for i, r in enumerate(rows)}
{2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}

Upvotes: 0

jadsq
jadsq

Reputation: 3382

Your issue is that you are not puting sub-dictionaries inside dataRows. The fix would be this:

for i, row in enumerate(rows):
    dataRows[row] = {}
    for key, value in data.items():
        dataRows[row][key] = value[i]

Upvotes: 7

Related Questions