Lets say I have a dictionary:
mydict = {"color":"green",
"type":"veg",
"fruit":"apple",
"level": 5
}
new_dict = {}
I would like to append the key "color" and "fruit" and their values receptively into the new_dict
. what is the easiest way to do that? Thank you.
You can try this:
new_dict = {x:mydict[x] for x in mydict if x in ('color','fruit')}
the easiest way is this:
new_dict["color"] = mydict["color"]
however, if you had a larger list of items you need to pass to a new dict, you could use the following:
items = ["color", "fruit"]
for item in items:
new_dict[item] = mydict[item]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With