I have a list of dicts from which I need to extract, into a new list, some elements. It works fine for one element:
d = [
{
"a": 1,
"b": {
"x": 3
},
"blah": 4
},
{
"a": 10,
"b": {
"x": 30
},
"blah": 40
},
]
z = [k["b"] for k in d]
print(z)
This outputs [{'x': 3}, {'x': 30}]
which is the extracted data.
I now realize that I also need to include in the extracted dict another element from the original one: a
(and its value).
I thought I would just take the value if b
and update()
it with a pair:
y = [k["b"].update({"a": k["a"]}) for k in d]
print(y)
This will not work (returns [None, None]
) as update()
does not return the resulting dict. A previous question led me to build a dict()
from the components:
x = [dict(a=k["a"], **k["b"]) for k in d]
print(x)
This crashes with
Traceback (most recent call last):
File "C:/dev/config/scratches/scratch_21.py", line 24, in <module>
x = [dict(a=k["a"], **k["b"]) for k in d]
File "C:/dev/config/scratches/scratch_21.py", line 24, in <listcomp>
x = [dict(a=k["a"], **k["b"]) for k in d]
TypeError: type object got multiple values for keyword argument 'a'
What does that mean? Specifically: what are the "multiple values" when there is only one for that key (an integer) ?