crusarovid
crusarovid

Reputation: 541

Converting Array of Python dictionaries to Python dictionary using comprehensions

I have a Python array of dictionaries that looks like this:

[
 {
  "pins": [1,2],
  "group": "group1"
 },
 {
  "pins": [3,4],
  "group": "group2"
 }
]

I want to convert this array of dictionaries into the following dictionary:

{ 1: "group1", 2: "group1", 3: "group2", 4: "group2" }

I wrote the following double for loop to accomplish this, but was curious if there is a more efficient way to do this (maybe a comprehension?):

new_dict = {}
for d in my_array:
    for pin in d['pins']:
        new_dict[pin] = d['group']

Upvotes: 1

Views: 50

Answers (1)

cs95
cs95

Reputation: 402493

Let's try a dictionary comprehension:

new_dict = {
    k : arr['group'] for arr in my_array for k in arr['pins']
}

This is equivalent to:

new_dict = {}
for arr in my_array:
    for k in arr['pins']:
        new_dict[k] = arr['group']

print(new_dict)
{1: 'group1', 2: 'group1', 3: 'group2', 4: 'group2'}

Upvotes: 3

Related Questions