Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add new key value for every dict of dict with list of dict

I have dict of dict:

a = {
    'a': {'id': 1},
    'b': {'id': 1},
    'c': {'id': 1}
}

And list of dict:

b = [{'word': 'foo'}, {'word': 'baz'}, {'word': 'bar'}]

I need update every dict from a to every value key word from b

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example:

a = {
    'a': {'id': 1, 'word': foo},
    'b': {'id': 1, 'word': baz},
    'c': {'id': 1, 'word': bar}
}

i try do it by the next way:

[
a.update(
    {
        'word': i
    }
)
for a in a.values()
for i in [
    df['word'] for df in b
    ]
]

but i have all new keys with last word bar:

    a = {
    'a': {'id': 1, 'word': bar},
    'b': {'id': 1, 'word': bar},
    'c': {'id': 1, 'word': bar}
}

How i can solve it?

>Solution :

Use zip to iterate over a and b concurrently:

for k, d in zip(a, b):
    a[k].update(d)

Result:

{'a': {'id': 1, 'word': 'foo'}, 
 'b': {'id': 1, 'word': 'baz'},
 'c': {'id': 1, 'word': 'bar'}}

You can also use a.values() as one of the arguments to zip:

for d1, d2 in zip(a.values(), b):
    d1.update(d2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading