Reputation: 51
Here's a minimal reproducible example:
from collections import OrderedDict
d = OrderedDict([('foo', 123),
('bar', 456)])
So I want to check if there's a foo
key in d
and if there's then I'd like to rewrite it as a single value of a list for a new hardcoded key:
print(d)
ordereddict([('bar', 456), ('newCoolHardcodedKey', [ordereddict([('foo', 123)])])])
Upvotes: 0
Views: 205
Reputation: 12221
You can use a generating expression (like a list comprehension, but returns an iterator instead of storing the temporary list in memory) to do this:
d = OrderedDict(
(
("newCoolHardcodedKey", OrderedDict([item])) if item[0] == "foo" else item
for item in d.items()
)
)
print(d)
OrderedDict([('newCoolHardcodedKey', OrderedDict([('foo', 123)])), ('bar', 456)])
The dict being ordered, the new element is where foo
was.
If you need the new element to go to the end, it might be easiest to test if d["foo"]
exists, and if so append the new ordered dict with its hard-coded key and delete the original entry for foo
:
if "foo" in d:
d["newCoolHardcodedKey"] = OrderedDict([("foo", d["foo"])])
del d["foo"]
print(d)
OrderedDict([('bar', 456), ('newCoolHardcodedKey', OrderedDict([('foo', 123)]))])
Performance considerations
If d
is large in your real application, the second solution is much better since it changes d
in place instead of making a copy.
Upvotes: 1