Pythonic dictionary traversal
I often find myself in situations where I need to traverse and parse a semi-complex JSON structure. During the traversal, there are certain dic开发者_如何学Gotionary keys
that are expected, and their values
need to be appropriately mapped to some object (foo.__dict__
).
Any remaining key/values that did not explicitly map to an object (foo.additional_attributes(**remaining)
) will need to be isolated and so can be handled as miscellaneous key/value attributes.
Is there some combination of build-in functions simplifying this kind of traversal, mapping, and isolation, making it more dynamic and Pythonic?
You can use the pop
method of dictionaries:
for key in expected_keys:
foo.__dict__[key] = d.pop(key)
foo.additional_attributes(**d)
精彩评论