Yun Chun
Yun Chun

Reputation: 11

How to convert list of dicts to dicts?

I have a list of dict that I am struggling to change to list of dicts:

x = [
    { # begin first and only dict in list
        '11': [{'bb': '224', 'cc': '14'}, {'bb': '254', 'cc': '16'}]
        , '22': [{'bb': '824', 'cc': '19'}]
    }
]

Which currently has a length of 1. i.e.:

print(len(x)) # 1

I intend to change it to list of dicts. i.e.:

desired = [
    { # begin first dict in list
        '11': [{'bb': '224', 'cc': '14'}, {'bb': '254', 'cc': '16'}]
    }
    , { # begin second dict in list
        '22': [{'bb': '824', 'cc': '19'}]
    }
]
    
print(len(desired)) # 2

What I tried:

dd = {}
for elem in x:
    for k,v in elem.items():
        dd[k] = v
print([dd])

print(len(dd)) # 2

Is there a better way or perhaps more efficient way?

Upvotes: 0

Views: 86

Answers (2)

Arka
Arka

Reputation: 986

Do you want the result to be 2 as you"ve got two keys (11 & 22) ? then try this:

print(len(x[0]))

Upvotes: 0

rbatt
rbatt

Reputation: 4807

Like others mentioned, there is nothing "wrong" with what you've tried. However, you might be interested in trying a list comprehension:

x_desired = [{k: v} for i in x for k, v in i.items()]

Like your attempted approach, this is effectively 2 for loops, the second nested within the first. In general, list comprehensions are considered fast and Pythonic.

Upvotes: 2

Related Questions