Home > Blockchain >  add new key value for every dict of dict with list of dict
add new key value for every dict of dict with list of dict

Time:04-04

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

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?

CodePudding user response:

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)

CodePudding user response:

I like the first answer...but along with your thinking, you just needed to get an index from enumerating the dictionary and use that to index the list.

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

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

c = [
    value.update({"word": b[index]["word"]})
    for index, (key, value) in enumerate(a.items())
]

print(a)
{
    "a": {"id": 1, "word": "foo"},
    "b": {"id": 1, "word": "baz"},
    "c": {"id": 1, "word": "bar"},
}

CodePudding user response:

This also works and uses a dictionary comprehension instead of a for loop:

a = {
    'a': {'id': 1},
    'b': {'id': 1},
    'c': {'id': 1}
}
b = [{'word': 'foo'}, {'word': 'baz'}, {'word': 'bar'}]
a = {k:{**a[k], **d} for k, d in zip(a, b)} 

Result:

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